import logging
import traceback
from ast import For
from flask import Flask, jsonify, json, request, session, make_response, send_file
from flask_cors import CORS
import math, time, os, copy
from datetime import timedelta
import xlrd
from controllers.aws_db import S3Operation
from controllers.db import *
from controllers.config import *
from controllers.common import *
from controllers.localization import *
from controllers.extreme_user_event_project import (
    extreme_user_api,
    extreme_user_down_api,
    extreme_user_schedule_api,
    extreme_user_schedule_down_api)

from controllers.match_numerical_conf import (
    match_numerical_conf_api,
    match_numerical_conf_down_api)

from controllers.buy_pid_reward_send import (
    buy_pid_reward_send_api,
    buy_reward_pid_list_api,
    buy_pid_reward_send_down_api)

from controllers.buy_pid_trigger_iap_send import (
    buy_pid_trigger_iap_send_api,
    buy_pid_trigger_iap_send_down_api)
from controllers.ava_event_project import (
    ava_event_project_api,
    ava_event_project_down_api,
    ava_event_project_sync_api,
    ava_event_project_sync_preprocessing_api)

from controllers.daily_deals_event_project import (
    daily_deals_event_project_api,
    daily_deals_event_project_down_api
)

from controllers.new_personal_event_project_v2 import (
    new_personal_event_project_v2_api,
    new_personal_event_project_v2_down_api
)

from controllers.strongest_sheriff_project_v2 import (
    strongest_sheriff_project_v2_api,
    strongest_sheriff_project_v2_down_api
)

from controllers.new_al_legion_event_project import (
    new_al_legion_event_project_api,
    new_al_legion_event_project_down_api
)

from controllers.old_al_legion_event_project import (
    old_al_legion_event_project_api,
    old_al_legion_event_project_down_api,
    old_al_legion_event_project_sync_preprocessing_api,
    old_al_legion_event_project_sync_api
)

from controllers.betting_event import (
    betting_event_project_api,
    betting_event_project_down_api,
    betting_event_schedule_api,
    betting_event_schedule_down_api,
    betting_event_schedule_timeline_api,
    betting_event_spider_api,
    betting_event_world_cup_schedule_api
)

from controllers.questionnaire import (
    questionnaire_project_api,
    questionnaire_project_down_api,
    questionnaire_schedule_api,
    questionnaire_schedule_down_api
)

from controllers.al_pay_gift_project import (
    al_pay_gift_project_api,
    al_pay_gift_project_down_api
)

from controllers.item_transform import (
    item_transform_project_api,
    item_transform_project_down_api
)
from controllers.public_index import (
    index_data_api,
    remark_delete_api,
    clone_data_api
    # pid_block_action_api
)

from controllers.common_buff import (
    common_buff_api,
    common_buff_down_api
)

from controllers.kindom_buff import (
    kindom_buff_api,
    kindom_buff_sync_api,
    kindom_buff_schedule_sync_api
)

from controllers.discount_store_proj import (
    discount_reward_type_list_api,
    discount_store_proj_api,
    discount_store_schedule_api,
    discount_store_json_api
)

from controllers.auction_event_project import (
    auction_event_project_api,
    auction_event_project_down_api
)

from controllers.joy_event_project import (
    joy_event_project_api,
    joy_event_project_down_api,
    joy_event_project_sync_api
)

from controllers.theme_event_project import (
    theme_event_project_sync_api,
    theme_event_project_api,
    theme_event_project_down_api
)

from controllers.shama_event_project import (
    shama_event_project_sync_api,
    shama_event_project_api,
    shama_event_project_down_api
)

from controllers.bandit_event_project import (
    bandit_event_project_sync_api,
    bandit_event_project_api,
    bandit_event_project_down_api
)

from controllers.check_tags import check_tags_api

from controllers.store_event_project import (
    store_event_project_api,
    store_event_project_down_api
)

from controllers.iap_coupon_project import (
    iap_coupon_project_api,
    iap_coupon_project_down_api
)

from controllers.conquest_match_event_project import (
    conquest_match_event_project_api,
    conquest_match_event_project_down_api,
    conquest_match_event_project_optimization_update_api,
    conquest_match_event_project_group_num_update_api
)

from controllers.dynamic_sub_game import (
    dynamic_sub_game_master_api,
    dynamic_sub_game_publish_api
)

from controllers.lucky_purchase import (
    lucky_purchase_api,
    lucky_purchase_down_api,
    lucky_purchase_reward_pool_api
)

from controllers.growth_ladder import (
    growth_ladder_api,
    growth_ladder_down_api
)

from controllers.growth_gift_project import (
    growth_gift_project_down_api,
    growth_gift_project_action_api,
    growth_gift_project_upload_api
)

from controllers.activity_battlepass import *
from controllers.universal_compare_api import *

from controllers.view_reward_replace_result import (
    view_reward_replace_result_api
)
# 请勿删除 ly_import_blueprint
from controllers.new_evip_shop_item import * 
from controllers.gui_zhen import *
from controllers.new_wg_lucky_wheel import *


CORS(app, resources=r'/*')

app.debug = True
app.SEND_FILE_MAX_AGE_DEFAULT = timedelta(seconds=1)
app.secret_key = 'locus'

app.register_blueprint(extreme_user_api, url_prefix='/')
app.register_blueprint(extreme_user_down_api, url_prefix='/')
app.register_blueprint(extreme_user_schedule_api, url_prefix='/')
app.register_blueprint(extreme_user_schedule_down_api, url_prefix='/')

app.register_blueprint(match_numerical_conf_api, url_prefix='/')
app.register_blueprint(match_numerical_conf_down_api, url_prefix='/')

app.register_blueprint(buy_pid_reward_send_api, url_prefix='/')
app.register_blueprint(buy_reward_pid_list_api, url_prefix='/')
app.register_blueprint(buy_pid_reward_send_down_api, url_prefix='/')

app.register_blueprint(buy_pid_trigger_iap_send_api, url_prefix='/')
app.register_blueprint(buy_pid_trigger_iap_send_down_api, url_prefix='/')

app.register_blueprint(ava_event_project_api, url_prefix='/')
app.register_blueprint(ava_event_project_down_api, url_prefix='/')
app.register_blueprint(ava_event_project_sync_api, url_prefix='/')
app.register_blueprint(ava_event_project_sync_preprocessing_api, url_prefix='/')

app.register_blueprint(daily_deals_event_project_api, url_prefix='/')
app.register_blueprint(daily_deals_event_project_down_api, url_prefix='/')
app.register_blueprint(new_personal_event_project_v2_api, url_prefix='/')
app.register_blueprint(new_personal_event_project_v2_down_api, url_prefix='/')
app.register_blueprint(strongest_sheriff_project_v2_api, url_prefix='/')
app.register_blueprint(strongest_sheriff_project_v2_down_api, url_prefix='/')

app.register_blueprint(new_al_legion_event_project_api, url_prefix='/')
app.register_blueprint(new_al_legion_event_project_down_api, url_prefix='/')

app.register_blueprint(old_al_legion_event_project_api, url_prefix='/')
app.register_blueprint(old_al_legion_event_project_down_api, url_prefix='/')
app.register_blueprint(old_al_legion_event_project_sync_preprocessing_api, url_prefix='/')
app.register_blueprint(old_al_legion_event_project_sync_api, url_prefix='/')

app.register_blueprint(betting_event_project_api, url_prefix='/')
app.register_blueprint(betting_event_project_down_api, url_prefix='/')
app.register_blueprint(betting_event_schedule_api, url_prefix='/')
app.register_blueprint(betting_event_schedule_down_api, url_prefix='/')
app.register_blueprint(betting_event_schedule_timeline_api, url_prefix='/')
app.register_blueprint(betting_event_spider_api, url_prefix='/')
app.register_blueprint(betting_event_world_cup_schedule_api, url_prefix='/')

app.register_blueprint(questionnaire_project_api, url_prefix='/')
app.register_blueprint(questionnaire_project_down_api, url_prefix='/')
app.register_blueprint(questionnaire_schedule_api, url_prefix='/')
app.register_blueprint(questionnaire_schedule_down_api, url_prefix='/')

app.register_blueprint(al_pay_gift_project_api, url_prefix='/')
app.register_blueprint(al_pay_gift_project_down_api, url_prefix='/')

app.register_blueprint(item_transform_project_api, url_prefix='/')
app.register_blueprint(item_transform_project_down_api, url_prefix='/')

app.register_blueprint(index_data_api, url_prefix='/')
app.register_blueprint(remark_delete_api, url_prefix='/')
app.register_blueprint(clone_data_api, url_prefix='/')
# app.register_blueprint(pid_block_action_api, url_prefix='/')

app.register_blueprint(common_buff_api, url_prefix='/')
app.register_blueprint(common_buff_down_api, url_prefix='/')

app.register_blueprint(kindom_buff_api, url_prefix='/')
app.register_blueprint(kindom_buff_sync_api, url_prefix='/')
app.register_blueprint(kindom_buff_schedule_sync_api, url_prefix='/')

app.register_blueprint(discount_reward_type_list_api, url_prefix='/')
app.register_blueprint(discount_store_proj_api, url_prefix='/')
app.register_blueprint(discount_store_schedule_api, url_prefix='/')
app.register_blueprint(discount_store_json_api, url_prefix='/')

app.register_blueprint(auction_event_project_api, url_prefix='/')
app.register_blueprint(auction_event_project_down_api, url_prefix='/')

app.register_blueprint(joy_event_project_api, url_prefix='/')
app.register_blueprint(joy_event_project_down_api, url_prefix='/')
app.register_blueprint(joy_event_project_sync_api, url_prefix='/')

app.register_blueprint(theme_event_project_sync_api, url_prefix='/')
app.register_blueprint(theme_event_project_api, url_prefix='/')
app.register_blueprint(theme_event_project_down_api, url_prefix='/')

app.register_blueprint(shama_event_project_sync_api, url_prefix='/')
app.register_blueprint(shama_event_project_api, url_prefix='/')
app.register_blueprint(shama_event_project_down_api, url_prefix='/')

app.register_blueprint(bandit_event_project_sync_api, url_prefix='/')
app.register_blueprint(bandit_event_project_api, url_prefix='/')
app.register_blueprint(bandit_event_project_down_api, url_prefix='/')

app.register_blueprint(check_tags_api, url_prefix='/')

app.register_blueprint(store_event_project_api, url_prefix='/')
app.register_blueprint(store_event_project_down_api, url_prefix='/')

app.register_blueprint(iap_coupon_project_api, url_prefix='/')
app.register_blueprint(iap_coupon_project_down_api, url_prefix='/')

app.register_blueprint(conquest_match_event_project_api, url_prefix='/')
app.register_blueprint(conquest_match_event_project_down_api, url_prefix='/')
app.register_blueprint(conquest_match_event_project_optimization_update_api, url_prefix='/')
app.register_blueprint(conquest_match_event_project_group_num_update_api, url_prefix='/')

app.register_blueprint(dynamic_sub_game_master_api, url_prefix='/')
app.register_blueprint(dynamic_sub_game_publish_api, url_prefix='/')

app.register_blueprint(lucky_purchase_api, url_prefix='/')
app.register_blueprint(lucky_purchase_down_api, url_prefix='/')
app.register_blueprint(lucky_purchase_reward_pool_api, url_prefix='/')

app.register_blueprint(growth_ladder_api, url_prefix='/')
app.register_blueprint(growth_ladder_down_api, url_prefix='/')

app.register_blueprint(activity_battlepass_project_api, url_prefix='/')
app.register_blueprint(activity_battlepass_project_down_api, url_prefix='/')

app.register_blueprint(growth_gift_project_down_api, url_prefix='/')
app.register_blueprint(growth_gift_project_action_api, url_prefix='/')
app.register_blueprint(growth_gift_project_upload_api, url_prefix='/')

app.register_blueprint(get_version_list_api, url_prefix='/')
app.register_blueprint(compare_version_api, url_prefix='/')
app.register_blueprint(compare_pid_api, url_prefix='/')
app.register_blueprint(get_effective_version_info_api, url_prefix='/')

app.register_blueprint(view_reward_replace_result_api, url_prefix='/')

app.register_blueprint(new_evip_shop_item_api, url_prefix='/')
app.register_blueprint(new_evip_shop_item_down_api, url_prefix='/')
app.register_blueprint(new_wg_lucky_wheel_api, url_prefix='/')
app.register_blueprint(gui_zhen_down_api, url_prefix='/')
app.register_blueprint(gui_zhen_api, url_prefix='/')
app.register_blueprint(new_wg_lucky_wheel_down_api, url_prefix='/')


# 请勿删除 ly_register_blueprint

sec_1sec = 1
sec_1min = 60 * sec_1sec
sec_1hour = 60 * sec_1min
sec_1day = 24 * sec_1hour


def ExcelData(model, excel_name):
    current_dir = os.path.dirname(os.path.realpath(__file__)) + "/uploads"

    excel_data = xlrd.open_workbook(current_dir+'/'+excel_name)

    doc_num = 21

    excel_result = {}
    if model == 'lucky_wheel':
        tbl = excel_data.sheet_by_name("wheel")
        for r_idx in range(1, tbl.nrows):
            pid = str(ToInt(tbl.cell(r_idx, 1).value))
            excel_result[pid] = {}
            for i in range(doc_num):
                title = tbl.cell(r_idx, 3+i).value
                info = tbl.cell(r_idx, 3+i+doc_num).value
                doc_id = str(int(i) + 1)

                if doc_id not in excel_result[pid]:
                    excel_result[pid][doc_id] = {}
                excel_result[pid][doc_id]['title'] = title
                excel_result[pid][doc_id]['info'] = info

        mysql_data = LuckyWheel.query.all()
        for d in mysql_data:
            project = str(d.project)
            if project in excel_result:
                basic_data = json.loads(d.basic)
                basic_data['lang'] = excel_result[project]

                sql_data = json.dumps(basic_data)
                LuckyWheel.query.filter_by(
                    project=project).update({'basic': sql_data})
    elif model == 'castle':
        tbl = excel_data.sheet_by_name("castle")
        for r_idx in range(1, tbl.nrows):
            pid = str(ToInt(tbl.cell(r_idx, 1).value))
            excel_result[pid] = {}
            for i in range(doc_num):
                title = tbl.cell(r_idx, 3+i).value
                info = tbl.cell(r_idx, 3+i+doc_num).value
                content = tbl.cell(r_idx, 3+i+doc_num*2).value
                doc_id = str(int(i) + 1)

                if doc_id not in excel_result[pid]:
                    excel_result[pid][doc_id] = {}
                excel_result[pid][doc_id]['title'] = title
                excel_result[pid][doc_id]['info'] = info
                excel_result[pid][doc_id]['content'] = content

        mysql_data = CastleLv.query.all()
        for d in mysql_data:
            project = str(d.project)
            if project in excel_result:
                basic_data = json.loads(d.basic)
                basic_data['localization'] = excel_result[project]
                sql_data = json.dumps(basic_data)
                CastleLv.query.filter_by(
                    project=project).update({'basic': sql_data})
    elif model == 'multiday_recharge':
        tbl = excel_data.sheet_by_name("multiday_recharge")
        for r_idx in range(1, tbl.nrows):
            pid = str(ToInt(tbl.cell(r_idx, 1).value))
            excel_result[pid] = {}
            for i in range(doc_num):
                title = tbl.cell(r_idx, 3+i).value
                doc_id = str(int(i) + 1)

                if doc_id not in excel_result[pid]:
                    excel_result[pid][doc_id] = {}
                excel_result[pid][doc_id]['title'] = title

        mysql_data = MultidayRecharge.query.all()
        for d in mysql_data:
            project = str(d.project)
            if project in excel_result:
                basic_data = json.loads(d.basic)
                basic_data['localization'] = excel_result[project]
                sql_data = json.dumps(basic_data)
                MultidayRecharge.query.filter_by(
                    project=project).update({'basic': sql_data})
    elif model == 'novice_recharge':
        excel_result = {}
        tbl = excel_data.sheet_by_name("novice_recharge")
        for r_idx in range(1, tbl.nrows):
            pid = str(ToInt(tbl.cell(r_idx, 1).value))
            goal = str(ToInt(tbl.cell(r_idx, 2).value))

            if pid not in excel_result:
                excel_result[pid] = {}
            for i in range(doc_num):
                content = tbl.cell(r_idx, 3+i).value
                doc_id = str(int(i) + 1)

                if doc_id not in excel_result[pid]:
                    excel_result[pid][doc_id] = {}
                    excel_result[pid][doc_id]['content'] = []
                excel_result[pid][doc_id]['content'].append(content)

        mysql_data = NoviceRecharge.query.all()
        for d in mysql_data:
            project = str(d.project)
            if project in excel_result:
                basic_data = json.loads(d.basic)
                basic_data['localization'] = excel_result[project]
                sql_data = json.dumps(basic_data)
                NoviceRecharge.query.filter_by(
                    project=project).update({'basic': sql_data})
    elif model == 'target_activity':

        tbl = excel_data.sheet_by_name("info")
        for r_idx in range(1, tbl.nrows):
            pid = str(ToInt(tbl.cell(r_idx, 1).value))
            excel_result[pid] = {}
            for i in range(doc_num):
                title = tbl.cell(r_idx, 3+i).value
                info = tbl.cell(r_idx, 3+i+doc_num).value
                content = tbl.cell(r_idx, 3+i+doc_num*2).value
                doc_id = str(int(i) + 1)
                if doc_id not in excel_result[pid]:
                    excel_result[pid][doc_id] = {}
                excel_result[pid][doc_id]['title'] = title
                excel_result[pid][doc_id]['info'] = info
                excel_result[pid][doc_id]['content'] = content

        mysql_data = TargetActivity.query.all()
        for d in mysql_data:
            project = str(d.project)
            if project in excel_result:
                basic_data = json.loads(d.basic)
                for doc_id in excel_result[project]:
                    basic_data['localization'][doc_id]['title'] = excel_result[project][doc_id]['title']
                    basic_data['localization'][doc_id]['info'] = excel_result[project][doc_id]['info']
                    basic_data['localization'][doc_id]['content'] = excel_result[project][doc_id]['content']
                sql_data = json.dumps(basic_data)
                TargetActivity.query.filter_by(
                    project=project).update({'basic': sql_data})

    elif model == 'target_activity_task':
        # pid
        tbl = excel_data.sheet_by_name("pid")
        pid = str(ToInt(tbl.cell(0, 1).value))

        project_data = TargetActivity.query.filter_by(project=pid).first()
        task_group_data = json.loads(project_data.task_group)

        mysql_data = TargetActivityList.query.all()
        task_id_detail_list = {}
        for d in mysql_data:
            tid = str(d.id)
            if tid not in task_id_detail_list:
                task_id_detail_list[tid] = {}
            task_id_detail_list[tid]['type'] = int(d.detail_type)
            task_id_detail_list[tid]['id'] = int(d.detail_id)
        # detail name
        detail_type_info = {}
        tbl = excel_data.sheet_by_name("detail_id")
        for r_idx in range(1, tbl.nrows):
            detail_type = str(ToInt(tbl.cell(r_idx, 1).value))
            detail_id = str(ToInt(tbl.cell(r_idx, 2).value))

            if detail_type not in detail_type_info:
                detail_type_info[detail_type] = {}
            if detail_id not in detail_type_info[detail_type]:
                detail_type_info[detail_type][detail_id] = {}

            for i in range(doc_num):
                doc_id = str(int(i) + 1)
                detail_name = tbl.cell(r_idx, 3+i).value
                detail_type_info[detail_type][detail_id][doc_id] = detail_name
        # task_name
        task_type_name_list = {}
        tbl = excel_data.sheet_by_name("task")
        for r_idx in range(1, tbl.nrows):
            task_type = str(int(float(tbl.cell(r_idx, 0).value)))
            for i in range(doc_num):
                doc_id = str(int(i) + 1)
                task_name = tbl.cell(r_idx, 3+i).value
                if task_type not in task_type_name_list:
                    task_type_name_list[task_type] = {}
                task_type_name_list[task_type][doc_id] = task_name

        task_doc_list = {}
        for i in range(len(task_group_data)):
            group_data = task_group_data[i]
            for j in range(len(group_data)):
                data = group_data[j]
                tid = str(data['tid'])
                task_id = str(data['task_id'])
                task_type = str(data['task_type'])

                # if tid not in task_id_detail_list:
                #   continue

                detail_type = str(task_id_detail_list[tid]['type'])
                detail_id = str(task_id_detail_list[tid]['id'])

                detail_level = str(data['detail'][1])
                # if task_type not in task_type_name_list:
                #   continue
                doc_list = copy.deepcopy(task_type_name_list[task_type])

                for doc_id in doc_list:
                    doc_name = doc_list[doc_id]

                    if 'STRING4' in doc_name:
                        doc_name = doc_name.replace('STRING4', detail_level)

                    if 'STRING2' in doc_name:

                        tmp_name = detail_type_info[detail_type][detail_id][doc_id]

                        doc_name = doc_name.replace('STRING2', tmp_name)

                    if doc_id not in task_doc_list:
                        task_doc_list[doc_id] = {}
                    task_doc_list[doc_id][task_id] = doc_name

        basic_data = json.loads(project_data.basic)
        for doc_id in basic_data['localization']:
            if doc_id in task_doc_list:
                basic_data['localization'][doc_id]['task_doc'] = task_doc_list[doc_id]

        sql_data = json.dumps(basic_data)
        TargetActivity.query.filter_by(project=pid).update({'basic': sql_data})

    elif model == 'continuous':
        tbl = excel_data.sheet_by_name("info")
        for r_idx in range(1, tbl.nrows):
            pid = str(ToInt(tbl.cell(r_idx, 1).value))
            excel_result[pid] = {}
            for i in range(doc_num):
                title = tbl.cell(r_idx, 3+i).value
                info = tbl.cell(r_idx, 3+i+doc_num).value
                forecast_slogan = tbl.cell(r_idx, 3+i+doc_num*2).value
                forecast_content = tbl.cell(r_idx, 3+i+doc_num*3).value
                doc_id = str(int(i) + 1)
                if doc_id not in excel_result[pid]:
                    excel_result[pid][doc_id] = {}
                excel_result[pid][doc_id]['title'] = title
                excel_result[pid][doc_id]['info'] = info
                excel_result[pid][doc_id]['forecast_slogan'] = forecast_slogan
                excel_result[pid][doc_id]['forecast_content'] = forecast_content

        mysql_data = ContinuousActivities.query.all()
        for d in mysql_data:
            project = str(d.project)
            if project in excel_result:
                basic_data = json.loads(d.basic)
                for doc_id in excel_result[project]:
                    if 'localization' not in basic_data:
                        basic_data['localization'] = {}
                    if doc_id not in basic_data['localization']:
                        basic_data['localization'][doc_id] = {}

                    basic_data['localization'][doc_id]['title'] = excel_result[project][doc_id]['title']
                    basic_data['localization'][doc_id]['info'] = excel_result[project][doc_id]['info']
                    basic_data['localization'][doc_id]['forecast_slogan'] = excel_result[project][doc_id]['forecast_slogan']
                    basic_data['localization'][doc_id]['forecast_content'] = excel_result[project][doc_id]['forecast_content']
                sql_data = json.dumps(basic_data)
                ContinuousActivities.query.filter_by(
                    project=project).update({'basic': sql_data})
    elif model == 'continuous_task':
        # pid
        tbl = excel_data.sheet_by_name("pid")
        pid = str(ToInt(tbl.cell(0, 1).value))

        project_data = ContinuousActivities.query.filter_by(
            project=pid).first()
        task_group_data = json.loads(project_data.task_group)

        mysql_data = ContinuousTaskList.query.all()
        task_id_detail_list = {}
        for d in mysql_data:
            tid = str(d.id)
            if tid not in task_id_detail_list:
                task_id_detail_list[tid] = {}
            task_id_detail_list[tid]['type'] = int(d.detail_type)
            task_id_detail_list[tid]['id'] = int(d.detail_id)
        # theme
        tbl = excel_data.sheet_by_name("theme")
        for r_idx in range(1, tbl.nrows):
            group_id = ToInt(tbl.cell(r_idx, 0).value)
            for i in range(doc_num):
                doc_id = str(int(i) + 1)
                theme_name = tbl.cell(r_idx, 1+i).value
                if 'doc' not in task_group_data[group_id]:
                    task_group_data[group_id]['doc'] = {}
                task_group_data[group_id]['doc'][doc_id] = theme_name
        # sub_theme
        tbl = excel_data.sheet_by_name("sub_theme")
        for r_idx in range(1, tbl.nrows):
            id_list = str(tbl.cell(r_idx, 0).value).split('_')

            group_id = int(id_list[0])
            task_id = int(id_list[1])

            for i in range(doc_num):
                doc_id = str(int(i) + 1)
                sub_theme_name = tbl.cell(r_idx, 1+i).value
                if 'doc' not in task_group_data[group_id]['task'][task_id]:
                    task_group_data[group_id]['task'][task_id]['doc'] = {}
                task_group_data[group_id]['task'][task_id]['doc'][doc_id] = sub_theme_name
        # detail name
        detail_type_info = {}
        tbl = excel_data.sheet_by_name("detail_id")
        for r_idx in range(1, tbl.nrows):
            detail_type = str(ToInt(tbl.cell(r_idx, 1).value))
            detail_id = str(ToInt(tbl.cell(r_idx, 2).value))

            if detail_type not in detail_type_info:
                detail_type_info[detail_type] = {}
            if detail_id not in detail_type_info[detail_type]:
                detail_type_info[detail_type][detail_id] = {}

            for i in range(doc_num):
                doc_id = str(int(i) + 1)
                detail_name = tbl.cell(r_idx, 3+i).value
                detail_type_info[detail_type][detail_id][doc_id] = detail_name

        # task_name
        task_type_name_list = {}
        tbl = excel_data.sheet_by_name("task")
        for r_idx in range(1, tbl.nrows):
            task_type = str(ToInt(tbl.cell(r_idx, 0).value))
            for i in range(doc_num):
                doc_id = str(int(i) + 1)
                task_name = tbl.cell(r_idx, 3+i).value
                if task_type not in task_type_name_list:
                    task_type_name_list[task_type] = {}
                task_type_name_list[task_type][doc_id] = task_name

        new_task_group_data = copy.deepcopy(task_group_data)

        for gid in range(len(new_task_group_data)):
            task_list = new_task_group_data[gid]['task']

            for task_id in range(len(task_list)):
                task_item_list = task_list[task_id]['task_item']

                for iid in range(len(task_item_list)):
                    tid = str(task_item_list[iid]['tid'])

                    detail_type = str(task_id_detail_list[tid]['type'])
                    detail_id = str(task_id_detail_list[tid]['id'])

                    detail_level = str(task_item_list[iid]['detail'][1])
                    task_type = str(task_item_list[iid]['task_type'])

                    doc_list = copy.deepcopy(task_type_name_list[task_type])

                    for doc_id in doc_list:
                        doc_name = doc_list[doc_id]

                        if 'STRING1' in doc_name:
                            doc_name = doc_name.replace(
                                'STRING1', detail_level)

                        if 'STRING2' in doc_name:

                            tmp_name = detail_type_info[detail_type][detail_id][doc_id]

                            doc_name = doc_name.replace('STRING2', tmp_name)

                        doc_list[doc_id] = doc_name
                    task_group_data[gid]['task'][task_id]['task_item'][iid]['doc'] = doc_list

        sql_data = json.dumps(task_group_data)
        ContinuousActivities.query.filter_by(
            project=pid).update({'task_group': sql_data})
    elif model == 'strongest_sheriff':
        tbl = excel_data.sheet_by_name("main")
        for r_idx in range(1, tbl.nrows):
            pid = str(ToInt(tbl.cell(r_idx, 1).value))
            excel_result[pid] = {}
            for i in range(doc_num):
                title = tbl.cell(r_idx, 3+i).value
                info = tbl.cell(r_idx, 3+i+doc_num).value
                content = tbl.cell(r_idx, 3+i+doc_num*2).value
                help_info = tbl.cell(r_idx, 3+i+doc_num*3).value
                doc_id = str(int(i) + 1)
                if doc_id not in excel_result[pid]:
                    excel_result[pid][doc_id] = {}
                excel_result[pid][doc_id]['title'] = title
                excel_result[pid][doc_id]['info'] = info
                excel_result[pid][doc_id]['content'] = content
                excel_result[pid][doc_id]['help_info'] = help_info

        sub_excel_result = {}
        tbl = excel_data.sheet_by_name("sub")
        for r_idx in range(1, tbl.nrows):
            pid = str(ToInt(tbl.cell(r_idx, 1).value))
            sub_pid = str(ToInt(tbl.cell(r_idx, 2).value))

            if pid not in sub_excel_result:
                sub_excel_result[pid] = {}

            if sub_pid not in sub_excel_result[pid]:
                sub_excel_result[pid][sub_pid] = {}

            for i in range(doc_num):
                title = tbl.cell(r_idx, 3+i).value
                goal_info = tbl.cell(r_idx, 3+i+doc_num).value
                help_info = tbl.cell(r_idx, 3+i+doc_num*2).value
                doc_id = str(int(i) + 1)
                if doc_id not in sub_excel_result[pid][sub_pid]:
                    sub_excel_result[pid][sub_pid][doc_id] = {}

                sub_excel_result[pid][sub_pid][doc_id]['title'] = title
                sub_excel_result[pid][sub_pid][doc_id]['info'] = goal_info
                sub_excel_result[pid][sub_pid][doc_id]['content'] = 'content'
                sub_excel_result[pid][sub_pid][doc_id]['help_info'] = help_info

                if 'sub_info' not in excel_result[pid][doc_id]:
                    excel_result[pid][doc_id]['sub_info'] = []

                tmp = {'title': title, 'goal_info': goal_info}
                excel_result[pid][doc_id]['sub_info'].append(tmp)

        mysql_data = StrongestSheriff.query.all()
        for d in mysql_data:
            project = str(d.project)
            if project in excel_result:
                basic_data = json.loads(d.basic)
                basic_data['localization'] = excel_result[project]
                sql_data = json.dumps(basic_data)
                StrongestSheriff.query.filter_by(
                    project=project).update({'basic': sql_data})

        mysql_data = StrongestSheriffSub.query.all()
        for d in mysql_data:
            sub_project = str(d.project)
            project = str(d.mid)
            if project in sub_excel_result:
                if sub_project in sub_excel_result[project]:
                    sub_basic_data = json.loads(d.basic)
                    sub_basic_data['localization'] = sub_excel_result[project][sub_project]
                    sub_sql_data = json.dumps(sub_basic_data)
                    StrongestSheriffSub.query.filter_by(
                        project=sub_project).update({'basic': sub_sql_data})

    elif model == 'monument':

        tbl = excel_data.sheet_by_name('pid')
        pid = str(ToInt(tbl.cell(0, 1).value))

        type_doc_content_list = {}

        tmp_name_list = ['title', 'info', 'forecast', 'begin',
                         'finished', 'unacommpolished', 'rank_unit', 'miss']

        for i in range(len(tmp_name_list)):
            name = tmp_name_list[i]

            tbl = excel_data.sheet_by_name(name)
            for r_idx in range(1, tbl.nrows):
                task_id = str(ToInt(tbl.cell(r_idx, 0).value))
                if task_id not in type_doc_content_list:
                    type_doc_content_list[task_id] = {}
                for i in range(doc_num):
                    doc_id = str(int(i) + 1)
                    if doc_id not in type_doc_content_list[task_id]:
                        type_doc_content_list[task_id][doc_id] = {}

                    type_doc_content_list[task_id][doc_id][name] = tbl.cell(
                        r_idx, 2+i).value

        TaskList = MonumentTask.query.all()
        all_task_list = {}
        for p in TaskList:
            id = str(p.id)
            type = str(p.type)
            all_task_list[id] = type
        # print(type_doc_content_list)
        data = Monument.query.all()
        for d in data:
            project = str(d.project)

            if pid != project:
                continue

            tasks = json.loads(d.tasks)

            result_data = {}
            for t in range(len(tasks)):
                id = str(tasks[t]['id'])
                type = all_task_list[id]

                task_id = str(tasks[t]['task_id'])

                task_num = str(tasks[t]['detail'][1])
                task_level = str(tasks[t]['detail'][2])
                task_target = str(tasks[t]['detail'][3])
                task_target = "{:,}".format(int(task_target))
                task_target = str(task_target)

                for doc_id in type_doc_content_list[task_id]:
                    title = type_doc_content_list[task_id][doc_id]['title']
                    info = type_doc_content_list[task_id][doc_id]['info']
                    forecast = type_doc_content_list[task_id][doc_id]['forecast']
                    begin = type_doc_content_list[task_id][doc_id]['begin']
                    finished = type_doc_content_list[task_id][doc_id]['finished']
                    unacommpolished = type_doc_content_list[task_id][doc_id]['unacommpolished']
                    rank_unit = type_doc_content_list[task_id][doc_id]['rank_unit']
                    # unreachable = type_doc_content_list[task_id][doc_id]['unreachable']
                    miss = type_doc_content_list[task_id][doc_id]['miss']

                    STRING1 = ''
                    STRING2 = ''
                    STRING3 = ''
                    if int(type) == 0 or int(type) == 2 or int(type) == 4:
                        STRING1 = task_target
                        STRING2 = task_level
                    elif int(type) == 1 or int(type) == 5 or int(type) == 7:
                        STRING1 = task_target
                    elif int(type) == 3:
                        STRING1 = task_level
                        STRING2 = task_num
                        STRING3 = task_target

                    title = title.replace('STRING1', STRING1)
                    title = title.replace('STRING2', STRING2)
                    title = title.replace('STRING3', STRING3)

                    info = info.replace('STRING1', STRING1)
                    info = info.replace('STRING2', STRING2)
                    info = info.replace('STRING3', STRING3)

                    forecast = forecast.replace('STRING1', STRING1)
                    forecast = forecast.replace('STRING2', STRING2)
                    forecast = forecast.replace('STRING3', STRING3)

                    begin = begin.replace('STRING1', STRING1)
                    begin = begin.replace('STRING2', STRING2)
                    begin = begin.replace('STRING3', STRING3)

                    finished = finished.replace('STRING1', STRING1)
                    finished = finished.replace('STRING2', STRING2)
                    finished = finished.replace('STRING3', STRING3)

                    unacommpolished = unacommpolished.replace(
                        'STRING1', STRING1)
                    unacommpolished = unacommpolished.replace(
                        'STRING2', STRING2)
                    unacommpolished = unacommpolished.replace(
                        'STRING3', STRING3)

                    rank_unit = rank_unit.replace('STRING1', STRING1)
                    rank_unit = rank_unit.replace('STRING2', STRING2)
                    rank_unit = rank_unit.replace('STRING3', STRING3)

                    # unreachable = unreachable.replace('STRING1',STRING1)
                    # unreachable = unreachable.replace('STRING2',STRING2)
                    # unreachable = unreachable.replace('STRING3',STRING3)

                    miss = miss.replace('STRING1', STRING1)
                    miss = miss.replace('STRING2', STRING2)
                    miss = miss.replace('STRING3', STRING3)

                    if doc_id not in result_data:
                        result_data[doc_id] = {}

                    if task_id not in result_data[doc_id]:
                        result_data[doc_id][task_id] = {}

                    result_data[doc_id][task_id]['title'] = title
                    result_data[doc_id][task_id]['info'] = info
                    result_data[doc_id][task_id]['content_forecast'] = forecast
                    result_data[doc_id][task_id]['content_begin'] = begin
                    result_data[doc_id][task_id]['content_finished'] = finished
                    result_data[doc_id][task_id]['content_unacommpolished'] = unacommpolished
                    result_data[doc_id][task_id]['rank_unit'] = rank_unit
                    # result_data[doc_id][task_id]['content_unreachable'] = unreachable
                    result_data[doc_id][task_id]['content_miss'] = miss

            sql_data = json.dumps(result_data)
            Monument.query.filter_by(project=project).update(
                {'localization': sql_data})
    elif model == 'territory_event':
        tbl = excel_data.sheet_by_name("info")
        for r_idx in range(1, tbl.nrows):
            pid = str(ToInt(tbl.cell(r_idx, 1).value))
            excel_result[pid] = {}
            for i in range(doc_num):
                title = tbl.cell(r_idx, 3+i).value
                sub_title = tbl.cell(r_idx, 3+i+doc_num).value
                info = tbl.cell(r_idx, 3+i+doc_num*2).value
                desc = tbl.cell(r_idx, 3+i+doc_num*3).value
                doc_id = str(int(i) + 1)

                if doc_id not in excel_result[pid]:
                    excel_result[pid][doc_id] = {}
                excel_result[pid][doc_id]['title'] = title
                excel_result[pid][doc_id]['sub_title'] = sub_title
                excel_result[pid][doc_id]['info'] = info
                excel_result[pid][doc_id]['desc'] = desc

        mysql_data = TerritoryEvent.query.all()
        for d in mysql_data:
            project = str(d.project)
            if project in excel_result:
                sql_data = json.dumps(excel_result[project])
                TerritoryEvent.query.filter_by(project=project).update({
                    'localization': sql_data})
    elif model == 'lohar_event':
        tbl = excel_data.sheet_by_name("info")
        for r_idx in range(1, tbl.nrows):
            pid = str(ToInt(tbl.cell(r_idx, 1).value))
            excel_result[pid] = {}
            for i in range(doc_num):
                title = tbl.cell(r_idx, 3+i).value
                desc = tbl.cell(r_idx, 3+i+doc_num).value
                info = tbl.cell(r_idx, 3+i+doc_num*2).value
                icon = tbl.cell(r_idx, 3+i+doc_num*3).value
                doc_id = str(int(i) + 1)

                if doc_id not in excel_result[pid]:
                    excel_result[pid][doc_id] = {}
                excel_result[pid][doc_id]['title'] = title
                excel_result[pid][doc_id]['desc'] = desc
                excel_result[pid][doc_id]['info'] = info
                excel_result[pid][doc_id]['icon'] = icon
        mysql_data = LoharEvent.query.all()
        for d in mysql_data:
            project = str(d.project)
            if project in excel_result:

                icon_lenth = 0
                basic_data = json.loads(d.basic)

                if 'icon' in basic_data['info_ui']:

                    if len(basic_data['info_ui']['icon']) > 0:
                        icon_lenth = len(
                            list(map(int, basic_data['info_ui']['icon'].split(","))))

                new_excel_data = {}
                for doc_id in excel_result[project]:
                    if doc_id not in new_excel_data:
                        new_excel_data[doc_id] = {}

                    if 'info' not in new_excel_data[doc_id]:
                        new_excel_data[doc_id]['info'] = {}

                    new_excel_data[doc_id]['title'] = excel_result[project][doc_id]['title']
                    new_excel_data[doc_id]['desc'] = excel_result[project][doc_id]['desc']
                    new_excel_data[doc_id]['info']['desc'] = excel_result[project][doc_id]['info']

                    if icon_lenth == 0:
                        new_excel_data[doc_id]['info']['icon'] = []
                    else:
                        icon_str_list = excel_result[project][doc_id]['icon'].split(
                            ",")

                        if len(icon_str_list) != icon_lenth:
                            print(icon_lenth, icon_str_list)
                        else:
                            new_excel_data[doc_id]['info']['icon'] = icon_str_list

                sql_data = json.dumps(new_excel_data)
                LoharEvent.query.filter_by(project=project).update(
                    {'localization': sql_data})

    elif model == 'special_map_dis':
        tpl_distribute = excel_data.sheet_by_name("distribute")
        result = {}
        tbl = excel_data.sheet_by_name("pid")
        pid = str(ToInt(tbl.cell(0, 1).value))
        # a1 = ToInt(tbl.cell(1, 1).value)
        tbl = excel_data.sheet_by_name("refresh_time_list")
        for r_idx in range(1, tbl.nrows):
            wild_id = str(ToInt(tbl.cell(r_idx, 0).value))
            lv = ToInt(tbl.cell(r_idx, 1).value)
            a0 = list(map(int, tbl.cell(r_idx, 2).value.split(",")))
            if wild_id not in result:
                result[wild_id] = {}
            if 'refresh_time_list' not in result[wild_id]:
                result[wild_id]['refresh_time_list'] = {}
            if 'a0' not in result[wild_id]['refresh_time_list']:
                result[wild_id]['refresh_time_list']['a0'] = []
            result[wild_id]['refresh_time_list']['a0'].append(a0)
            if 'a1' not in result[wild_id]['refresh_time_list']:
                a1 = ToInt(tbl.cell(r_idx, 3).value)
                result[wild_id]['refresh_time_list']['a1'] = a1
        tmp_result = {}
        tbl = excel_data.sheet_by_name("distribute")
        for r_idx in range(1, tbl.nrows):
            wild_id = str(ToInt(tbl.cell(r_idx, 0).value))
            max_lv = str(ToInt(tbl.cell(r_idx, 1).value))
            wild_lv = str(ToInt(tbl.cell(r_idx, 2).value))

            if wild_id not in tmp_result:
                tmp_result[wild_id] = {}

            if max_lv not in tmp_result[wild_id]:
                tmp_result[wild_id][max_lv] = {}

            for i in range(3, 14, 2):
                a1 = str(ToInt(tbl.cell(r_idx, i).value))
                n1 = ToInt(tbl.cell(r_idx, i+1).value)

                tmp = [int(wild_id), int(wild_lv), n1]

                if a1 not in tmp_result[wild_id][max_lv]:
                    tmp_result[wild_id][max_lv][a1] = []

                tmp_result[wild_id][max_lv][a1].append(tmp)

        for wild_id in tmp_result:

            for max_lv in tmp_result[wild_id]:
                if 'distribute' not in result[wild_id]:
                    result[wild_id]['distribute'] = []

                result[wild_id]['distribute'].append(
                    tmp_result[wild_id][max_lv])

        SpecialMapDis.query.filter_by(project=pid).update(
            {'conf': json.dumps(result)})

    elif model == 'new_alliance_event':
        tbl = excel_data.sheet_by_name("info")
        for r_idx in range(1, tbl.nrows):
            pid = str(ToInt(tbl.cell(r_idx, 1).value))
            excel_result[pid] = {}
            for i in range(doc_num):
                title = tbl.cell(r_idx, 3+i).value
                info = tbl.cell(r_idx, 3+i+doc_num).value
                content = tbl.cell(r_idx, 3+i+doc_num*2).value
                help_info = tbl.cell(r_idx, 3+i+doc_num*3).value
                doc_id = str(int(i) + 1)

                if doc_id not in excel_result[pid]:
                    excel_result[pid][doc_id] = {}
                excel_result[pid][doc_id]['title'] = title
                excel_result[pid][doc_id]['info'] = info
                excel_result[pid][doc_id]['content'] = content
                excel_result[pid][doc_id]['help_info'] = help_info
        mysql_data = NewAllianceEvent.query.all()
        for d in mysql_data:
            project = str(d.project)
            if project in excel_result:
                new_excel_data = {}
                for doc_id in excel_result[project]:
                    if doc_id not in new_excel_data:
                        new_excel_data[doc_id] = {}

                    new_excel_data[doc_id]['title'] = excel_result[project][doc_id]['title']
                    new_excel_data[doc_id]['info'] = excel_result[project][doc_id]['info']
                    new_excel_data[doc_id]['content'] = excel_result[project][doc_id]['content']
                    new_excel_data[doc_id]['help_info'] = excel_result[project][doc_id]['help_info']

                sql_data = json.dumps(new_excel_data)
                NewAllianceEvent.query.filter_by(project=project).update({
                    'localization': sql_data})
    elif model == 'new_personal_event':
        tbl = excel_data.sheet_by_name("info")
        for r_idx in range(1, tbl.nrows):
            pid = str(ToInt(tbl.cell(r_idx, 1).value))
            excel_result[pid] = {}
            for i in range(doc_num):
                title = tbl.cell(r_idx, 3+i).value
                info = tbl.cell(r_idx, 3+i+doc_num).value
                content = tbl.cell(r_idx, 3+i+doc_num*2).value
                help_info = tbl.cell(r_idx, 3+i+doc_num*3).value
                doc_id = str(int(i) + 1)

                if doc_id not in excel_result[pid]:
                    excel_result[pid][doc_id] = {}
                excel_result[pid][doc_id]['title'] = title
                excel_result[pid][doc_id]['info'] = info
                excel_result[pid][doc_id]['content'] = content
                excel_result[pid][doc_id]['help_info'] = help_info
        mysql_data = NewPersonalEvent.query.all()
        for d in mysql_data:
            project = str(d.project)
            if project in excel_result:
                new_excel_data = {}
                for doc_id in excel_result[project]:
                    if doc_id not in new_excel_data:
                        new_excel_data[doc_id] = {}

                    new_excel_data[doc_id]['title'] = excel_result[project][doc_id]['title']
                    new_excel_data[doc_id]['info'] = excel_result[project][doc_id]['info']
                    new_excel_data[doc_id]['content'] = excel_result[project][doc_id]['content']
                    new_excel_data[doc_id]['help_info'] = excel_result[project][doc_id]['help_info']

                sql_data = json.dumps(new_excel_data)
                NewPersonalEvent.query.filter_by(project=project).update({
                    'localization': sql_data})
    elif model == 'make_cake_event':
        tbl = excel_data.sheet_by_name("info")
        for r_idx in range(1, tbl.nrows):
            pid = str(ToInt(tbl.cell(r_idx, 1).value))
            excel_result[pid] = {}
            for i in range(doc_num):
                title = tbl.cell(r_idx, 3+i).value
                info = tbl.cell(r_idx, 3+i+doc_num).value
                desc = tbl.cell(r_idx, 3+i+doc_num*2).value
                exp = tbl.cell(r_idx, 3+i+doc_num*3).value
                unlock = tbl.cell(r_idx, 3+i+doc_num*4).value
                doc_id = str(int(i) + 1)
                if doc_id not in excel_result[pid]:
                    excel_result[pid][doc_id] = {}
                excel_result[pid][doc_id]['title'] = title
                excel_result[pid][doc_id]['info'] = info
                excel_result[pid][doc_id]['desc'] = desc
                excel_result[pid][doc_id]['exp'] = exp
                excel_result[pid][doc_id]['unlock'] = unlock.split(",")
                excel_result[pid][doc_id]['unlock'].insert(0, "")

        mysql_data = MakeCakeEvent.query.all()
        for d in mysql_data:
            project = str(d.project)
            if project in excel_result:
                new_excel_data = {}
                for doc_id in excel_result[project]:
                    if doc_id not in new_excel_data:
                        new_excel_data[doc_id] = {}
                    new_excel_data[doc_id]['title'] = excel_result[project][doc_id]['title']
                    new_excel_data[doc_id]['info'] = excel_result[project][doc_id]['info']
                    new_excel_data[doc_id]['desc'] = excel_result[project][doc_id]['desc']
                    new_excel_data[doc_id]['exp'] = excel_result[project][doc_id]['exp']
                    new_excel_data[doc_id]['unlock'] = excel_result[project][doc_id]['unlock']

                sql_data = json.dumps(new_excel_data)
                MakeCakeEvent.query.filter_by(project=project).update({
                    'localization': sql_data})
    elif model == 'notice_event':
        tbl = excel_data.sheet_by_name("main")
        for r_idx in range(1, tbl.nrows):
            pid = str(ToInt(tbl.cell(r_idx, 1).value))
            excel_result[pid] = {}
            for i in range(doc_num):
                title = tbl.cell(r_idx, 3+i).value
                desc = tbl.cell(r_idx, 3+i+doc_num).value
                if 3+i+doc_num*2 >= tbl.ncols:
                    info = ''
                else:
                    info = tbl.cell(r_idx, 3+i+doc_num*2).value

                doc_id = str(int(i) + 1)
                if doc_id not in excel_result[pid]:
                    excel_result[pid][doc_id] = {}
                excel_result[pid][doc_id]['title'] = title
                excel_result[pid][doc_id]['desc'] = desc
                excel_result[pid][doc_id]['info'] = info


        info_config = {}
        localization_id = 0
        tbl = excel_data.sheet_by_name("info_config")
        for r_idx in range(1, tbl.nrows):
            if tbl.cell(r_idx, 1).value == '':
                continue
            pid = str(ToInt(tbl.cell(r_idx, 1).value))
            info_ui = ToInt(tbl.cell(r_idx, 2).value)

            if pid not in excel_result:
                result_data[pid] = {}
                localization_id = 0
            else:
                localization_id += 1

            ##info_config
            if pid not in info_config:
                info_config[pid] = []
            tmp = {
                'localization_id': localization_id,
                'info_ui': info_ui
            }
            info_config[pid].append(tmp)

            for i in range(doc_num):
                info_title = tbl.cell(r_idx, 3+i).value
                info_desc = tbl.cell(r_idx, 3+i+doc_num).value
                doc_id = str(int(i) + 1)
                if doc_id not in excel_result[pid]:
                    excel_result[pid][doc_id] = {}

                if 'info_new' not in excel_result[pid][doc_id]:
                    excel_result[pid][doc_id]['info_new'] = {}

                if str(localization_id) not in excel_result[pid][doc_id]['info_new']:
                    excel_result[pid][doc_id]['info_new'][str(localization_id)] = {}

                excel_result[pid][doc_id]['info_new'][str(localization_id)]['info_title'] = info_title
                excel_result[pid][doc_id]['info_new'][str(localization_id)]['info_desc'] = info_desc

        mysql_data = NoticeEvent.query.all()
        for d in mysql_data:
            project = str(d.project)
            if project in excel_result:
                new_excel_data = {'localization':{}, 'info_config':[]}
                for doc_id in excel_result[project]:
                    if doc_id not in new_excel_data['localization']:
                        new_excel_data['localization'][doc_id] = {}
                    new_excel_data['localization'][doc_id]['title'] = excel_result[project][doc_id]['title']
                    new_excel_data['localization'][doc_id]['desc'] = excel_result[project][doc_id]['desc']
                    new_excel_data['localization'][doc_id]['info_new'] = excel_result[project][doc_id]['info_new']
                    if 'info' not in excel_result[project][doc_id]:
                        new_excel_data['localization'][doc_id]['info'] = ''
                    else:
                        new_excel_data['localization'][doc_id]['info'] = excel_result[project][doc_id]['info']

                if project in info_config:
                    new_excel_data['info_config'] = info_config[project]
                NoticeEvent.query.filter_by(project=project).update({'localization': json.dumps(new_excel_data)})

    elif model == 'battle_pass':
        battle_pass_list = {}
        tbl = excel_data.sheet_by_name("task")
        for r_idx in range(1, tbl.nrows):
            tid = str(ToInt(tbl.cell(r_idx, 0).value))
            idx = str(ToInt(tbl.cell(r_idx, 1).value))

            if tid not in battle_pass_list:
                battle_pass_list[tid] = {}



            type = str(ToInt(tbl.cell(r_idx, 2).value))
            check_idx = tbl.cell(r_idx, 3).value

            if type not in battle_pass_list[tid]:
                battle_pass_list[tid][type] = {}


            if check_idx == '':
                detail = []
            else:
                check_idx = ToInt(check_idx)
                compare_type = ToInt(tbl.cell(r_idx, 4).value)
                value_list = str(tbl.cell(r_idx, 5).value)
                if ',' in value_list:
                    value_list = list(map(int, value_list.split(",")))
                else:
                    value_list = [ToInt(value_list)]

                detail = [check_idx, compare_type, value_list]

            factor_idx = ToInt(tbl.cell(r_idx, 6).value)
            factor = ToInt(tbl.cell(r_idx, 7).value)
            factor = [factor_idx, factor]

            label = tbl.cell(r_idx, 8).value

            battle_pass_list[tid][type]['type'] = int(type)
            battle_pass_list[tid][type]['factor'] = factor
            battle_pass_list[tid][type]['label'] = label

            if 'detail' not in battle_pass_list[tid][type]:
                battle_pass_list[tid][type]['detail'] = []
            battle_pass_list[tid][type]['detail'].append(detail)

        new_battle_pass_list = {}
        for tid in battle_pass_list:
            for score_type in battle_pass_list[tid]:
                item = battle_pass_list[tid][score_type]
                tmp = {
                    'value': int(tid),
                    'type': item['type'],
                    'detail': item['detail'],
                    'factor': item['factor'],
                    'label': item['label']
                }
                if tid not in new_battle_pass_list:
                    new_battle_pass_list[tid] = []
                new_battle_pass_list[tid].append(tmp)
        filename = "battle_pass_task.json"
        current_dir = os.path.dirname(os.path.realpath(__file__)) + "/static"
        fh = open(current_dir+"/"+filename, "w")
        json.dump(new_battle_pass_list, fh,
                  sort_keys=True, separators=(',', ':'))
    elif model == 'battle_pass_info':
        tbl = excel_data.sheet_by_name("info")
        for r_idx in range(1, tbl.nrows):
            pid = str(ToInt(tbl.cell(r_idx, 0).value))
            excel_result[pid] = {}
            for i in range(doc_num):
                doc = tbl.cell(r_idx, 3+i).value
                title = tbl.cell(r_idx, 3+i+doc_num).value
                doc_id = str(int(i) + 1)
                if doc_id not in excel_result[pid]:
                    excel_result[pid][doc_id] = {}
                excel_result[pid][doc_id]['doc'] = doc
                excel_result[pid][doc_id]['title'] = title
        mysql_data = BattlePassTask.query.all()
        for d in mysql_data:
            project = str(d.idx)
            data = json.loads(d.data)
            if project in excel_result:
                data['localization'] = excel_result[project]
                sql_data = json.dumps(data)
                BattlePassTask.query.filter_by(
                    idx=project).update({'data': sql_data})
    elif model == 'chronicle':
        excel_result = {}
        field_list = ['title','info','content_forecast','content_begin','content_finished','content_miss','content_unacommpolished','rank_unit']
        for x in range(len(field_list)):
            field = field_list[x]
            tbl = excel_data.sheet_by_name(field)
            for r_idx in range(1, tbl.nrows):
                type_id = str(ToInt(tbl.cell(r_idx, 0).value))
                # idx = str(ToInt(tbl.cell(r_idx, 1).value))
                if type_id not in excel_result:
                    excel_result[type_id] = {}
                for i in range(doc_num):
                    if field == 'title':
                        title = tbl.cell(r_idx, 3+i).value
                    else:
                        title = tbl.cell(r_idx, 2+i).value
                    doc_id = str(int(i) + 1)
                    if doc_id not in excel_result[type_id]:
                        excel_result[type_id][doc_id] = {}
                    if field == 'title':
                        if field not in excel_result[type_id][doc_id]:
                            excel_result[type_id][doc_id][field] = []
                        excel_result[type_id][doc_id][field].append(title)
                    else:
                        excel_result[type_id][doc_id][field] = title
        localization = {}
        mysql_data = Chronicle.query.all()
        for d in mysql_data:
            project = str(d.project)
            tasks = json.loads(d.tasks)
            tmp_type_id_list = {}
            for x in range(len(tasks)):
                task_id = str(tasks[x]['task_id'])
                type_id = str(tasks[x]['detail'][0])
                has_rank = tasks[x]['has_rank']
                num = str(tasks[x]['detail'][3])
                level = str(tasks[x]['detail'][2])
                if type_id not in tmp_type_id_list:
                    tmp_type_id_list[type_id] = 0
                else:
                    tmp_type_id_list[type_id] += 1
                for doc_id in excel_result[type_id]:
                    if doc_id not in localization:
                        localization[doc_id] = {}
                    if task_id not in localization[doc_id]:
                        localization[doc_id][task_id] = {}
                    doc_list = excel_result[type_id][doc_id]
                    for field in doc_list:
                        if field == 'title':
                            info = doc_list[field][tmp_type_id_list[type_id]]
                        else:
                            info = doc_list[field]

                        if int(num) > 0:
                            info = info.replace('STRING1', num)
                        if int(level) > 0:
                            info = info.replace('STRING2', level)

                        # if has_rank == 1 and field in ['content_forecast','content_begin','content_finished','content_miss','content_unacommpolished']:
                        #     info = ''
                        # if has_rank == 0 and field == 'rank_unit':
                        #     info = ''

                        localization[doc_id][task_id][field] = info

            Chronicle.query.filter_by(project=project).update({'localization': json.dumps(localization)})

    elif model == 'lost_battlefield':
        name_list = ["alliance","svr"]
        excel_result = {}
        for n in range(len(name_list)):
            name = name_list[n]
            tbl = excel_data.sheet_by_name(name)
            for r_idx in range(1, tbl.nrows):
                pid = str(ToInt(tbl.cell(r_idx, 1).value))
                id = str(ToInt(tbl.cell(r_idx, 2).value))
                num = 0
                if int(id) == 1:
                    project_data = LostBattlefield.query.filter_by(project=pid).first()
                    achievement = json.loads(project_data.achievement)
                num = achievement[name][int(id)-1]['task'][2]

                if pid not in excel_result:
                    excel_result[pid] = {}

                if name == 'alliance':
                    task_id = 10000 + (int(id) -1)
                else:
                    task_id = 20000 + (int(id) -1)

                for i in range(doc_num):
                    title = tbl.cell(r_idx, 4+i).value
                    info = tbl.cell(r_idx, 4+i+doc_num).value
                    desc = tbl.cell(r_idx, 4+i+doc_num*2).value

                    desc = desc.replace('STRING0', str(num))

                    doc_id = str(int(i) + 1)
                    if doc_id not in excel_result[pid]:
                        excel_result[pid][doc_id] = {}

                    if 'achievement' not in excel_result[pid][doc_id]:
                        excel_result[pid][doc_id]['achievement'] = {}

                    if 'alliance' not in excel_result[pid][doc_id]['achievement']:
                        excel_result[pid][doc_id]['achievement']['alliance'] = []

                    if 'svr' not in excel_result[pid][doc_id]['achievement']:
                        excel_result[pid][doc_id]['achievement']['svr'] = []

                    tmp = {
                        "task_id":task_id,
                        "title":title,
                        "info":info,
                        "desc":desc
                    }
                    if name == 'alliance':
                        pass
                    excel_result[pid][doc_id]['achievement'][name].append(tmp)

        mysql_data = LostBattlefield.query.all()
        for d in mysql_data:
            project = str(d.project)
            if project in excel_result:
                sql_data = json.dumps(excel_result[project])
                LostBattlefield.query.filter_by(project=project).update({'localization': sql_data})

    elif model == 'lost_achievenemt':
        tbl = excel_data.sheet_by_name("info")
        for r_idx in range(1, tbl.nrows):
            pid = str(ToInt(tbl.cell(r_idx, 1).value))
            excel_result[pid] = {}
            for i in range(doc_num):
                title = tbl.cell(r_idx, 3+i).value
                info = tbl.cell(r_idx, 3+i+doc_num).value
                content = tbl.cell(r_idx, 3+i+doc_num*2).value
                help_info = tbl.cell(r_idx, 3+i+doc_num*3).value
                doc_id = str(int(i) + 1)
                if doc_id not in excel_result[pid]:
                    excel_result[pid][doc_id] = {}
                excel_result[pid][doc_id]['title'] = title
                excel_result[pid][doc_id]['info'] = info
                excel_result[pid][doc_id]['content'] = content
                excel_result[pid][doc_id]['help_info'] = help_info

        name_list = ["user","alliance", 'svr']
        for n in range(len(name_list)):
            name = name_list[n]
            tbl = excel_data.sheet_by_name(name)
            for r_idx in range(1, tbl.nrows):
                pid = str(ToInt(tbl.cell(r_idx, 1).value))
                id = str(ToInt(tbl.cell(r_idx, 2).value))
                if pid not in excel_result:
                    excel_result[pid] = {}

                for i in range(doc_num):
                    title = tbl.cell(r_idx, 4+i).value
                    info = tbl.cell(r_idx, 4+i+doc_num).value
                    doc_id = str(int(i) + 1)
                    if doc_id not in excel_result[pid]:
                        excel_result[pid][doc_id] = {}
                    if 'task_info' not in excel_result[pid][doc_id]:
                        excel_result[pid][doc_id]['task_info'] = []
                    tmp = {
                        "title":str(title),
                        "info":str(info)
                    }
                    excel_result[pid][doc_id]['task_info'].append(tmp)

        mysql_data = LostAchievenemtProj.query.all()
        for d in mysql_data:
            project = str(d.project)
            if project in excel_result:
                sql_data = json.dumps(excel_result[project])
                LostAchievenemtProj.query.filter_by(project=project).update({
                    'localization': sql_data})
    elif model == 'multi_growth_gift_project':
        tbl = excel_data.sheet_by_name("info")
        for r_idx in range(1, tbl.nrows):
            pid = str(ToInt(tbl.cell(r_idx, 1).value))
            excel_result[pid] = {'entrance_title':{}}
            for i in range(doc_num):
                title = tbl.cell(r_idx, 3+i).value
                doc_id = str(int(i) + 1)
                excel_result[pid]['entrance_title'][doc_id] = title

        mysql_data = MultiGrowthGiftProject.query.all()
        for d in mysql_data:
            project = str(d.project)
            if project in excel_result:
                sql_data = json.dumps(excel_result[project])
                MultiGrowthGiftProject.query.filter_by(project=project).update({'localization': sql_data})

    elif model == 'target_activity_proj':

        tbl = excel_data.sheet_by_name("info")
        for r_idx in range(1, tbl.nrows):
            pid = str(ToInt(tbl.cell(r_idx, 1).value))
            excel_result[pid] = {}
            for i in range(doc_num):
                title = tbl.cell(r_idx, 3+i).value
                info = tbl.cell(r_idx, 3+i+doc_num).value
                content = tbl.cell(r_idx, 3+i+doc_num*2).value
                doc_id = str(int(i) + 1)
                if doc_id not in excel_result[pid]:
                    excel_result[pid][doc_id] = {}
                excel_result[pid][doc_id]['title'] = title
                excel_result[pid][doc_id]['info'] = info
                excel_result[pid][doc_id]['content'] = content

        mysql_data = TargetActivityProj.query.all()
        for d in mysql_data:
            project = str(d.project)
            if project in excel_result:
                localization = json.loads(d.localization)
                for doc_id in excel_result[project]:
                    localization[doc_id]['title'] = excel_result[project][doc_id]['title']
                    localization[doc_id]['info'] = excel_result[project][doc_id]['info']
                    localization[doc_id]['content'] = excel_result[project][doc_id]['content']
                sql_data = json.dumps(localization)
                TargetActivityProj.query.filter_by(
                    project=project).update({'localization': sql_data})

    elif model == 'recharge_rebate_project':
        recharge_rebate_project_doc(excel_data, RechargeRebateProject)

    elif model == 'continuous_activities_task_content':
        continuous_activities_task_content_doc(excel_data, STATIC_PATH)

    elif model == 'continuous_activities_proj':
        continuous_activities_proj_doc(excel_data, ContinuousActivitiesProj)

    elif model == 'novice_recharge_rebate_project':
        novice_recharge_rebate_project_doc(excel_data, NoviceRechargeRebateProject)

    elif model == 'target_activity_task_content':
        target_activity_task_content_doc(excel_data, STATIC_PATH)

    elif model == 'backflow_main_proj':
        backflow_main_proj_doc(excel_data, BackflowMainProj)

    elif model == 'score_theme_battle_pass_project':
        score_theme_battle_pass_project_doc(excel_data, ScoreThemeBattlePassProject)

    elif model == 'task_theme_battle_pass_project':
        task_theme_battle_pass_project_doc(excel_data, TaskThemeBattlePassProject)

    elif model == 'task_theme_bp_task_content':
        task_theme_bp_task_content_doc(excel_data)

    elif model == 'score_theme_bp_task_content':
        score_theme_bp_task_content_doc(excel_data)

    elif model =='shop_project':
        shop_project_doc(excel_data, ShopProject)

    elif model == 'western_shadow_menu_project':
        western_shadow_menu_project_doc(excel_data, WesternShadowMenuProject)

    elif model == 'duel_yard_event_proj':
        duel_yard_event_proj_doc(excel_data, DuelYardEventProj)

    elif model == 'extreme_user_event_project':
        extreme_user_event_project_task(excel_data, ExtremeUserTaskPool, db)

    elif model == 'kvk_event_project':
        kvk_event_project_doc(excel_data, KvkEventProject)

    elif model == 'ava_event_project':
        ava_event_project_doc(excel_data, AvaEventProject)

    elif model == 'kvk_event_score':
        kvk_event_score_doc(excel_data)

    elif model == 'new_personal_event_project_v2':
        new_personal_event_project_v2_doc(excel_data, NewPersonalEventProjectV2)

    elif model == 'strongest_sheriff_project_v2':
        strongest_sheriff_project_v2_doc(excel_data, StrongestSheriffProjectV2, StrongestSheriffProjectV2Sub)

    elif model == 'old_al_legion_event_project':
        old_al_legion_event_project_doc(excel_data, OldAlLegionEventProject)

    elif model == 'theme_event_project':
        theme_event_project_doc(excel_data, ThemeEventProject)

    elif model == 'shama_event_project':
        shama_event_project_doc(excel_data, ShamaEventProject)

    elif model == 'bandit_event_project':
        bandit_event_project_doc(excel_data, BanditEventProject)

    db.session.commit()


@app.route('/upload/<field>', methods=['GET', 'POST'])
def UploadFile(field):

    f = request.files['file']
    base_path = os.path.abspath(os.path.dirname(__file__))
    upload_path = os.path.join(base_path, 'uploads', f.filename)
    f.save(upload_path)
    ExcelData(field, f.filename)

    return jsonify({"msg": "上传文件成功", "ret": 0})

@app.route('/strongest_sheriff_index', methods=['GET'])
def strongest_sheriff_index():
    data = StrongestSheriff.query.all()
    result = []
    for d in data:
        project = int(d.project)
        info = json.loads(d.basic)
        title = info['localization']['1']['title']
        remark = info['remark'] if 'remark' in info else ''
        tmp = {"project": project, "title": title, 'remark': remark}
        result.append(tmp)
    return jsonify(result)

@app.route('/update_strongest_sheriff_remark', methods=['GET', 'POST'])
def update_strongest_sheriff_remark():
    update_data = json.loads(request.data)
    pid = update_data['project']
    remark = update_data['remark']

    project_data = StrongestSheriff.query.filter_by(project=pid).first()
    basic = json.loads(project_data.basic)
    basic['remark'] = remark
    project_data.basic = json.dumps(basic)
    db.session.commit()
    return jsonify({'ret': 0, 'msg': '更新remark成功'})


@app.route('/strongest_sheriff_basic/<field>/<int:pid>', methods=['GET'])
def strongest_sheriff_basic(field, pid=0):
    if pid != 0:
        session['pid'] = pid
    pid = session['pid']

    project_data = StrongestSheriff.query.filter_by(project=pid).first()
    if (project_data is None):
        result = {'msg': '找不到数据'}
    else:
        result = {}
        if field == 'basic':

            result['basic'] = json.loads(project_data.basic)
            result['project'] = pid

        elif field == 'delete':
            project_data = StrongestSheriff.query.filter_by(
                project=pid).first()
            db.session.delete(project_data)
            db.session.commit()

            sub_project_data = StrongestSheriffSub.query.filter_by(
                mid=pid).all()
            for s in sub_project_data:
                db.session.delete(s)
                db.session.commit()

            project_data = StrongestSheriff.query.filter_by(
                project=pid).first()
            if (project_data is None):
                result = {'msg': '删除成功', 'ret': 0}
            else:
                result = {'msg': '删除失败', 'ret': 1}

        elif field == 'clone':
            result = {'msg': '添加成功', 'ret': 0}
            new_project_data = StrongestSheriff(
                basic=project_data.basic, reward=project_data.reward)
            db.session.add(new_project_data)
            db.session.commit()
            new_project_id = new_project_data.project

            sub_project_data = StrongestSheriffSub.query.filter_by(
                mid=pid).order_by(StrongestSheriffSub.project).all()

            for s in sub_project_data:
                new_sub_project_data = StrongestSheriffSub(
                    basic=s.basic, mid=new_project_id, reward=s.reward)
                db.session.add(new_sub_project_data)
                db.session.commit()

            if (new_project_id is None):
                result = {'msg': '添加失败', 'ret': 2}

        elif field == 'rank_reward':
            reward = rewardList()
            reward = reward['name']
            rank_reward = json.loads(project_data.reward)
            bonus_list = rank_reward['rank_reward']['user']
            result_bonus = {}
            for idx in range(len(bonus_list)):
                _from = bonus_list[idx]['from']
                _to = bonus_list[idx]['to']
                reward_data = bonus_list[idx]['reward']

                for i in range(len(reward_data)):
                    item_type = reward_data[i]['a'][0]
                    item_id = reward_data[i]['a'][1]
                    item_num = reward_data[i]['a'][2]
                    item_rate = 1
                    item_price = 100
                    item_pos = idx
                    if item_type in reward and str(item_id) in reward[item_type]:
                        item_name = reward[item_type][str(item_id)]
                    else:
                        item_name = 'ERROR'

                    if item_pos not in result_bonus:
                        result_bonus[item_pos] = {}
                        result_bonus[item_pos]['from'] = _from
                        result_bonus[item_pos]['to'] = _to
                        result_bonus[item_pos]['reward'] = []

                    tmp = {"type": item_type, "id": item_id, "num": item_num, "rate": item_rate,
                           "price": item_price, "pos": item_pos, "name": item_name, "from": _from, "to": _to}

                    result_bonus[item_pos]['reward'].append(tmp)
            result = {'project': project_data.project, 'bonus': result_bonus}

        elif field == 'sub_event_id':

            data = StrongestSheriffSub.query.order_by(
                StrongestSheriffSub.project).filter_by(mid=pid)
            result = {'project': pid, 'sub': []}
            for d in data:
                sub_id = int(d.project)
                result['sub'].append(
                    {'name': str(sub_id), 'title': "阶段_"+str(sub_id)})

    return jsonify(result)


@app.route('/strongest_sheriff_sub_basic/<field>/<int:pid>/<int:sub_pid>', methods=['GET'])
def strongest_sheriff_sub_basic(field, pid, sub_pid):

    project_data = StrongestSheriffSub.query.filter_by(
        project=sub_pid, mid=pid).first()

    result = {}
    if field == 'basic':
        basic_data = json.loads(project_data.basic)
        if 'score_id_list' not in basic_data:
            basic_data['score_id_list'] = []

        result['basic'] = basic_data

        result['project'] = project_data.mid
        result['sub_project'] = project_data.project

        doc_data = loadDocument()

        score_type_list = []

        mysql_data = StrongestSheriffTask.query.order_by(
            StrongestSheriffTask.doc_id).all()
        task_list = []
        for p in mysql_data:
            id = int(p.id)
            num = str(p.num)
            doc_id = str(p.doc_id)

            doc_name = doc_data['doc_scoring_rule'][doc_id]['content'] + \
                "-" + str(doc_id)

            if 'STRING0' in doc_name:
                doc_name = doc_name.replace('STRING0', num)

            tmp = {"label": doc_name, 'value': id}
            score_type_list.append(tmp)

        result['score_type_list'] = score_type_list

    elif field == 'addstage':

        result = {'msg': '添加成功', 'ret': 0}
        new_project_data = StrongestSheriffSub(
            basic=project_data.basic, mid=pid, reward=project_data.reward)
        db.session.add(new_project_data)
        db.session.commit()

        project_id = new_project_data.project
        if (project_id is None):
            result = {'msg': '添加失败', 'ret': 2}

    elif field == 'sub_rank_reward':
        reward = rewardList()
        reward = reward['name']
        rank_reward = json.loads(project_data.reward)
        bonus_list = rank_reward['rank_reward']['user']
        result_bonus = {}
        for idx in range(len(bonus_list)):
            _from = bonus_list[idx]['from']
            _to = bonus_list[idx]['to']
            reward_data = bonus_list[idx]['reward']

            for i in range(len(reward_data)):
                item_type = reward_data[i]['a'][0]
                item_id = reward_data[i]['a'][1]
                item_num = reward_data[i]['a'][2]
                item_rate = 1
                item_price = 100
                item_pos = idx
                if item_type in reward and str(item_id) in reward[item_type]:
                    item_name = reward[item_type][str(item_id)]
                else:
                    item_name = 'ERROR'

                if item_pos not in result_bonus:
                    result_bonus[item_pos] = {}
                    result_bonus[item_pos]['from'] = _from
                    result_bonus[item_pos]['to'] = _to
                    result_bonus[item_pos]['reward'] = []

                tmp = {"type": item_type, "id": item_id, "num": item_num, "rate": item_rate,
                       "price": item_price, "pos": item_pos, "name": item_name, "from": _from, "to": _to}

                result_bonus[item_pos]['reward'].append(tmp)

        result = {'project': project_data.mid,
                  'sub_project': project_data.project, 'bonus': result_bonus}
    elif field == 'sub_goal_reward':
        reward = rewardList()
        reward = reward['name']
        rank_reward = json.loads(project_data.reward)
        bonus_list = rank_reward['goal_reward']['user']
        result_bonus = {}
        for idx in range(len(bonus_list)):
            _from = bonus_list[idx]['from']
            _to = bonus_list[idx]['to']
            reward_data = bonus_list[idx]['reward']

            for i in range(len(reward_data)):
                item_type = reward_data[i]['a'][0]
                item_id = reward_data[i]['a'][1]
                item_num = reward_data[i]['a'][2]
                item_rate = 1
                item_price = 100
                item_pos = idx
                if item_type in reward and str(item_id) in reward[item_type]:
                    item_name = reward[item_type][str(item_id)]
                else:
                    item_name = 'ERROR'

                if item_pos not in result_bonus:
                    result_bonus[item_pos] = {}
                    result_bonus[item_pos]['from'] = _from
                    result_bonus[item_pos]['to'] = _to
                    result_bonus[item_pos]['reward'] = []
                tmp = {"type": item_type, "id": item_id, "num": item_num, "rate": item_rate,
                       "price": item_price, "pos": item_pos, "name": item_name, "from": _from, "to": _to}

                result_bonus[item_pos]['reward'].append(tmp)

        result = {'project': project_data.mid,
                  'sub_project': project_data.project, 'bonus': result_bonus}

    return jsonify(result)


@app.route('/update_strongest_sheriff', methods=['GET', 'POST'])
def update_strongest_sheriff():

    update_data = json.loads(request.data)
    project_id = update_data['project']

    update_type = update_data['update_type']

    update_data.pop('update_type')

    if update_type == 'basic':

        event_ui = int(update_data['event_ui'])
        castle_lv = int(update_data['castle_lv'])
        rank_limit = int(update_data['rank_limit'])

        localization = update_data['localization']

        project_data =  StrongestSheriff.query.filter_by(project=project_id).first()
        basic = json.loads(project_data.basic)
        basic['event_ui'] = event_ui
        basic['castle_lv'] = castle_lv
        basic['localization'] = localization
        basic['rank_limit'] = rank_limit
        project_data.basic = json.dumps(basic)
        db.session,commit()

        # sql_data = {'event_ui': event_ui, 'castle_lv': castle_lv,
        #             'localization': localization, 'rank_limit': rank_limit}

        # StrongestSheriff.query.filter_by(project=project_id).update({
        #     'basic': json.dumps(sql_data)})
    elif update_type == 'sub_basic':

        sub_project = update_data['sub_project']
        project = update_data['project']

        event_ui = int(update_data['event_ui'])
        castle_lv = int(update_data['castle_lv'])
        rank_limit = int(update_data['rank_limit'])
        stage_type = int(update_data['stage_type'])

        score_id_list = update_data['score_id_list']

        localization = update_data['localization']

        sql_data = {'score_id_list': score_id_list, 'event_ui': event_ui, 'castle_lv': castle_lv,
                    'stage_type': stage_type, 'localization': localization, 'rank_limit': rank_limit}

        StrongestSheriffSub.query.filter_by(project=sub_project, mid=project).update({
            'basic': json.dumps(sql_data)})

    elif update_type == 'rank_reward':
        rank_reward_data = []

        bonus_list = update_data['bonus']

        for idx in bonus_list:
            data = bonus_list[idx]
            _from = int(data['from'])
            _to = int(data['to'])
            reward = []
            for r_idx in range(len(data['reward'])):
                item_type = int(data['reward'][r_idx]['type'])
                item_id = int(data['reward'][r_idx]['id'])
                item_num = int(data['reward'][r_idx]['num'])
                tmp = {}
                tmp['a'] = [item_type, item_id, item_num]
                reward.append(tmp)

            rank_reward_data.append(
                {"from": _from, "to": _to, "reward": reward})
        mysql_data = {}
        mysql_data['rank_reward'] = {"user": rank_reward_data}

        StrongestSheriff.query.filter_by(project=project_id).update(
            {'reward': json.dumps(mysql_data)})

    elif update_type == 'sub_rank_reward':

        project_id = int(update_data['project'])
        sub_project_id = int(update_data['sub_project'])

        project_data = StrongestSheriffSub.query.filter_by(
            project=sub_project_id, mid=project_id).first()

        mysql_reward_data = json.loads(project_data.reward)

        rank_reward_data = []

        bonus_list = update_data['bonus']

        for idx in bonus_list:
            data = bonus_list[idx]
            _from = int(data['from'])
            _to = int(data['to'])
            reward = []
            for r_idx in range(len(data['reward'])):
                item_type = int(data['reward'][r_idx]['type'])
                item_id = int(data['reward'][r_idx]['id'])
                item_num = int(data['reward'][r_idx]['num'])
                tmp = {}
                tmp['a'] = [item_type, item_id, item_num]
                reward.append(tmp)

            rank_reward_data.append(
                {"from": _from, "to": _to, "reward": reward})

        mysql_reward_data['rank_reward'] = {"user": rank_reward_data}

        StrongestSheriffSub.query.filter_by(mid=project_id).update(
            {'reward': json.dumps(mysql_reward_data)})

    elif update_type == 'sub_goal_reward':

        project_id = update_data['project']
        sub_project_id = update_data['sub_project']

        project_data = StrongestSheriffSub.query.filter_by(
            project=sub_project_id, mid=project_id).first()

        mysql_reward_data = json.loads(project_data.reward)

        rank_reward_data = []

        bonus_list = update_data['bonus']

        for idx in bonus_list:
            data = bonus_list[idx]
            _from = 1
            _to = int(data['to'])
            reward = []
            for r_idx in range(len(data['reward'])):
                item_type = int(data['reward'][r_idx]['type'])
                item_id = int(data['reward'][r_idx]['id'])
                item_num = int(data['reward'][r_idx]['num'])
                tmp = {}
                tmp['a'] = [item_type, item_id, item_num]
                reward.append(tmp)
            rank_reward_data.append(
                {"from": _from, "to": _to, "reward": reward})

        mysql_reward_data['goal_reward'] = {"user": rank_reward_data}

        StrongestSheriffSub.query.filter_by(project=sub_project_id, mid=project_id).update({
            'reward': json.dumps(mysql_reward_data)})
    db.session.commit()
    return jsonify({'msg': '更新成功', 'ret': 0})


@app.route('/down_strongest_sheriff/<int:is_push>', methods=['GET', 'POST'])
def down_strongest_sheriff(is_push):

    result_data = {}
    project_data = StrongestSheriff.query.all()
    for p in project_data:
        project_id = str(p.project)
        basic = json.loads(p.basic)
        if 'remark' in basic:
            del basic['remark']
        reward = json.loads(p.reward)

        result_data['event_main_type'] = 61
        result_data[project_id] = {}
        result_data[project_id]['basic'] = {}
        result_data[project_id]['basic']['event_ui'] = int(basic['event_ui'])
        result_data[project_id]['localization'] = basic['localization']
        result_data[project_id]['castle_lv'] = int(basic['castle_lv'])

        result_data[project_id]['reward'] = reward

        result_data[project_id]['extern0'] = {}
        result_data[project_id]['extern1'] = {}
        result_data[project_id]['sub_id_list'] = []

        result_data[project_id]['extern0']['rank_limit'] = int(
            basic['rank_limit'])
        result_data[project_id]['extern0']['sub_rank_limit'] = []
        result_data[project_id]['extern0']['sub_rank_reward'] = []

        sub_project_data = StrongestSheriffSub.query.order_by(
            StrongestSheriffSub.mid).filter_by(mid=project_id).all()

        for s in sub_project_data:
            sub_basic = json.loads(s.basic)
            reward = json.loads(s.reward)
            sub_project = int(s.project)

            rank_limit = int(sub_basic['rank_limit'])

            result_data[project_id]['extern0']['sub_rank_limit'].append(
                rank_limit)

            result_data[project_id]['extern0']['sub_rank_reward'].append(
                reward['rank_reward'])

            result_data[project_id]['sub_id_list'].append(sub_project)

        result_data[project_id]['sub_id_list'].sort()

    response = DownLoad('strongest_sheriff_project', result_data, is_push)

    return response


@app.route('/down_strongest_sheriff_sub/<int:is_push>', methods=['GET', 'POST'])
def down_strongest_sheriff_sub(is_push):

    with open(STATIC_PATH + 'strongest_sheriff_sub_cac_score.json', encoding='utf8') as f:
        sub_cac_score = json.load(f)

    mysql_data = StrongestSheriffTask.query.all()
    task_list = {}
    for p in mysql_data:
        id = int(p.id)
        type = int(p.type)
        id_list = list(map(int, p.id_list.split(",")))
        num = int(p.num)
        score = int(p.score)
        doc_id = int(p.doc_id)
        target_unit = int(p.target_unit)
        show_type = int(p.show_type)

        if show_type == 0:
            show = []
        else:
            show = [{"type":show_type,"value":0}]

        num = target_unit * num

        task_list[str(id)] = {"type": type, "id_list": id_list,
                              "num": num, "score": score, "doc_id": doc_id, "target_unit": target_unit, 'show': show}

    result_data = {}
    project_data = StrongestSheriffSub.query.order_by(
        StrongestSheriffSub.project).all()
    for p in project_data:
        project_id = str(p.project)
        mid = str(p.mid)
        basic = json.loads(p.basic)
        reward = json.loads(p.reward)

        result_data['event_main_type'] = 62
        result_data[project_id] = {}
        result_data[project_id]['basic'] = {}
        result_data[project_id]['basic']['event_ui'] = int(basic['event_ui'])
        result_data[project_id]['localization'] = basic['localization']
        result_data[project_id]['castle_lv'] = int(basic['castle_lv'])
        result_data[project_id]['stage_type'] = int(basic['stage_type'])

        result_data[project_id]['reward'] = reward

        result_data[project_id]['extern0'] = {}
        result_data[project_id]['extern1'] = {}

        result_data[project_id]['extern0']['rank_limit'] = int(
            basic['rank_limit'])
        result_data[project_id]['calc_score'] = {}
        calc_score_list = []
        for i in range(len(basic['score_id_list'])):
            score_id = str(basic['score_id_list'][i])
            calc_score_list.append(task_list[score_id])

        result_data[project_id]['calc_score']['score_type_list'] = calc_score_list

    response = DownLoad('strongest_sheriff_sub_project', result_data, is_push)

    return response


@app.route('/target_activity_index', methods=['GET'])
def target_activity_index():
    data = TargetActivity.query.all()
    result = []
    for d in data:
        project = int(d.project)
        info = json.loads(d.basic)
        title = info['localization']['1']['title']
        tmp = {"project": project, "title": title}
        result.append(tmp)
    return jsonify(result)


@app.route('/target_activity_basic/<field>/<int:pid>', methods=['GET'])
def target_activity_basic(field, pid=0):
    project_data = TargetActivity.query.filter_by(project=pid).first()
    if (project_data is None):
        result = {'msg': '找不到数据'}
    else:
        result = {}
        if field == 'basic':

            result['basic'] = json.loads(project_data.basic)
            result['project'] = pid

        elif field == 'delete':
            project_data = TargetActivity.query.filter_by(project=pid).first()
            db.session.delete(project_data)
            db.session.commit()
            project_data = TargetActivity.query.filter_by(project=pid).first()
            if (project_data is None):
                result = {'msg': '删除成功', 'ret': 0}
            else:
                result = {'msg': '删除失败', 'ret': 1}

        elif field == 'clone':
            result = {'msg': '添加成功', 'ret': 0}
            new_project_data = TargetActivity(
                basic=project_data.basic, task_group=project_data.task_group)
            db.session.add(new_project_data)
            db.session.commit()

            project_id = new_project_data.project
            if (project_id is None):
                result = {'msg': '添加失败', 'ret': 2}

    return jsonify(result)


@app.route('/update_target_activity', methods=['GET', 'POST'])
def update_target_activity():

    update_data = json.loads(request.data)
    project_id = update_data['project']

    update_type = update_data['update_type']

    update_data.pop('update_type')

    if update_type == 'basic':

        event_ui = int(update_data['event_ui'])
        task_refresh = int(update_data['task_refresh'])
        localization = update_data['localization']

        sql_data = {'event_ui': event_ui,
                    'task_refresh': task_refresh, 'localization': localization}

        TargetActivity.query.filter_by(project=project_id).update(
            {'basic': json.dumps(sql_data)})

    db.session.commit()
    return jsonify({'msg': '更新成功', 'ret': 0})


@app.route('/target_activity_task/<int:task>/<int:pid>', methods=['GET'])
def target_activity_task(task,pid):

    project_data = TargetActivity.query.filter_by(project=pid).first()
    result = {}
    task_group = json.loads(project_data.task_group)
    if len(task_group) < task + 1:
        task = 0
    task_item = task_group[task]
    reward_item_list = rewardList()
    reward_item_list = reward_item_list['name']
    task_item_list = []
    for i in range(len(task_item)):
        item = task_item[i]
        level = item['detail'][1]
        task_type = item['task_type']
        tid = item['tid']
        task_id = item['task_id']
        target = item['target']
        task_unit = item['task_unit']

        reward = RewardToDic(item['reward'],0,reward_item_list)

        tmp = {'task_id': task_id, 'level': level, 'task_type': task_type, 'tid': tid,
               'reward': reward[0], 'target': target, 'LevelActive': False, 'task_unit': task_unit}
        task_item_list.append(tmp)

    TaskList = TargetActivityList.query.all()
    all_task_list = []
    for p in TaskList:
        id = int(p.id)
        label = p.label
        tmp = {"value": id, "label": label}
        all_task_list.append(tmp)

    result['all_task_list'] = all_task_list
    result['task_item_list'] = task_item_list
    result['project'] = project_data.project

    return jsonify(result)


@app.route('/target_activity_proj', methods=['GET'])
def target_activity_proj():
    data = TargetActivityProj.query.all()
    result = []
    for d in data:
        project = int(d.project)
        localization = json.loads(d.localization)
        title = localization['1']['title'] if '1' in localization else 'No title'
        remark = d.remark
        tmp = {"project": project, "title": title, 'remark': remark}
        result.append(tmp)
    return jsonify(result)

@app.route('/get_target_task_content', methods=['GET'])
def get_target_task_content():
    result = {}
    task_label_list = []
    with open(STATIC_PATH + 'target_task_content.json', encoding='utf-8') as f:
        content = json.load(f)
    task_content = content['task_type']
    detail_content = content['detail_type']
    task_cp_detail_list = {}

    for k, v in task_content.items():
        tmp = {'label': k + '--' + task_content[k]['name'],
               'task_type': int(k),
               'detail_type': task_content[k]['detail_type']}
        task_label_list.append(tmp)

        detail_type = str(task_content[k]['detail_type'])
        if detail_type != '' and detail_type != '10':
            task_cp_detail_list[k] = detail_content[detail_type]

    result['task_label_list'] = task_label_list
    result['task_content'] = task_content
    result['detail_content'] = detail_content
    result['task_cp_detail_list'] = task_cp_detail_list
    return jsonify(result)

@app.route('/target_activity_proj_action', methods=['GET', 'POST'])
def target_activity_proj_action():
    update_data = json.loads(request.data)
    result = {'msg': '成功','ret':0}
    _type = update_data['type']
    project = update_data['project']
    project_data = TargetActivityProj.query.filter_by(project=project).first()

    if _type == 'remark':
        project_data.remark = update_data['remark']
        db.session.commit()

    elif _type == 'clone':
        result = {'msg': '克隆成功', 'ret': 0}
        new_project_data = TargetActivityProj(basic=project_data.basic,
                                              task_group=project_data.task_group,
                                              remark = project_data.remark,
                                              localization=project_data.localization)
        db.session.add(new_project_data)
        db.session.commit()

        project_id = new_project_data.project
        if project_id is None:
            result = {'msg': '克隆失败', 'ret': 2}

    elif _type == 'delete':
        project_data = TargetActivityProj.query.filter_by(project=project).first()
        db.session.delete(project_data)
        db.session.commit()
        project_data = TargetActivityProj.query.filter_by(project=project).first()
        if (project_data is None):
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}

    elif _type == 'basic':
        basic = json.loads(project_data.basic)
        if 'calendar_reward' not in basic:
            basic['calendar_reward'] = []

        if 'calendar_doc_id' not in basic:
            basic['calendar_doc_id'] = 1

        if '_tag' not in basic:
            basic['_tag'] = []

        result['basic'] = {'event_ui': basic['event_ui'],
                           'task_refresh': basic['task_refresh'],
                           'calendar_doc_id': basic['calendar_doc_id'],
                           'calendar_reward': basic['calendar_reward'],
                           '_check_tags': basic['_tag']}

        task_group = json.loads(project_data.task_group)
        new_task_group = {}
        for i in range(len(task_group)):
            task_item = task_group[i]
            new_task_group[str(i)] = []
            for ii in range(len(task_item)):
                item = task_item[ii]
                detail_id = item['detail'][0]
                level = item['detail'][1]
                tid = item['task_type']
                target = item['target']
                task_unit = item['task_unit'] if 'task_unit' in item else 1

                tmp = {'level': level, 'tid': tid,
                       'reward': item['reward'], 'target': target, 'task_unit': task_unit, 'idx': ii,
                       'detail_id': detail_id}
                new_task_group[str(i)].append(tmp)

        doc_content = GetDocByFilename('target_event')
        doc_id_list = []
        for k, v in doc_content.items():
            doc_id_list.append({
                'value': int(k),
                'label': '{0}-{1}'.format(k, v['title'])
                })

        result['task_group'] = new_task_group
        result['doc_id_list'] = doc_id_list

    elif _type == 'update_basic':
        with open(STATIC_PATH + 'target_task_content.json', encoding='utf-8') as f:
            content = json.load(f)
        task_content = content['task_type']
        detail_content = content['detail_type']

        # 初始化 task_doc内容
        localization = json.loads(project_data.localization)
        for v in localization.values():
            v['task_doc'] = {}

        # 69 消耗x个A 品质的 英雄奖章, 74 累计消耗X个A品质教官升星道具, 76 累计消耗A品质教官专属碎片X个
        special_doc = {'69': {'1': '蓝色', '2': '紫色', '3': '金色',},
                       '74': {'1': '紫色', '2': '橙色'},
                       '76': {'1': '紫色', '2': '橙色'}}

        event_ui = update_data['event_ui']
        task_refresh = update_data['task_refresh']
        calendar_doc_id = update_data['calendar_doc_id']
        taskItem = update_data['taskItem']
        calendar_reward = update_data['calendar_reward']
        task_group = []
        for k, v in taskItem.items():
            for i in range(len(taskItem[k])):
                node = taskItem[k][i]
                task_id = (int(k) + 1)*1000 + i
                node['task_id'] = task_id
                tid_str = str(node['tid'])
                detail_type = task_content[tid_str]['detail_type']
                op_type = task_content[tid_str]['op_type']
                if not task_content[tid_str]['detail_type']:
                    detail_id = 0
                    detail_type = 0
                else:
                    detail_id = node['detail_id'] if 'detail_id' in node else 0

                if not task_content[tid_str]['level_flag']:
                    level = 0
                else:
                    level = node['level'] if 'level' in node else 0

                if not task_content[tid_str]['time_flag']:
                    task_unit = 1
                else:
                    task_unit = node['task_unit'] if 'task_unit' in node else 1

                # if task_content[tid_str]['id_flag']:
                #     d_type = str(task_content[tid_str]['detail_type'])
                #     for detail_node in detail_content[d_type]:
                #         if detail_node['id'] == detail_id:
                #             string2_detail_doc = detail_node['detail_doc']
                #             break

                # # 更新的时候也更新文案的task_doc内容
                # for lang_str in range(1, DOC_NUM+1):
                #     lang_id = str(lang_str)
                #     if 'task_doc' in task_content[tid_str] and lang_id in task_content[tid_str]['task_doc']:
                #         cur_doc = task_content[tid_str]['task_doc'][lang_id]
                #     else:
                #         cur_doc = ''
                #     # if 'STRING0' in cur_doc:
                #     #     cur_doc = cur_doc.replace('STRING0', str(node['target']))
                #     if 'STRING2' in cur_doc:
                #         cur_doc = cur_doc.replace('STRING2', string2_detail_doc[lang_id])
                #     if 'STRING4' in cur_doc:
                #         # 特殊处理69, 74, 76
                #         if tid_str in special_doc:
                #             if tid_str == '69':
                #                 for detail_node in detail_content['6']:
                #                     if detail_node['id'] == level:
                #                         string4 = detail_node['detail_doc'][lang_id]
                #                         cur_doc = cur_doc.replace('STRING4', string4)
                #                         break
                #             if tid_str == '74':
                #                 for detail_node in detail_content['11']:
                #                     if detail_node['id'] == level:
                #                         string4 = detail_node['detail_doc'][lang_id]
                #                         cur_doc = cur_doc.replace('STRING4', string4)
                #                         break
                #             if tid_str == '76':
                #                 for detail_node in detail_content['12']:
                #                     if detail_node['id'] == level:
                #                         string4 = detail_node['detail_doc'][lang_id]
                #                         cur_doc = cur_doc.replace('STRING4', string4)
                #                         break

                #             # cur_doc = cur_doc.replace('STRING4', special_doc[tid_str][str(level)])

                #         else:
                #             cur_doc = cur_doc.replace('STRING4', str(level))
                #     # if 'STRING1' in cur_doc:
                #     #     cur_doc = cur_doc.replace('STRING1', str(task_unit))
                #     localization[lang_id]['task_doc'][str(task_id)] = cur_doc

                node['task_unit'] = task_unit
                node['detail'] = [detail_id, level, op_type]
                node['task_type'] = int(tid_str)
                # node['task_type'] 就是 tid
                del node['tid']
                if 'idx' in node:
                    del node['idx']
                if 'detail_id' in node:
                    del node['detail_id']
                if 'level' in node:
                    del node['level']
            task_group.append(taskItem[k])

        basic = json.loads(project_data.basic)
        basic['event_ui'] = event_ui
        basic['task_refresh'] = task_refresh
        basic['calendar_doc_id'] = calendar_doc_id
        basic['calendar_reward'] = calendar_reward
        basic['_tag'] = update_data['_check_tags']
        project_data.basic = json.dumps(basic)
        project_data.task_group = json.dumps(task_group)
        project_data.localization = json.dumps(localization)
        db.session.commit()

    return jsonify(result)

@app.route('/target_activity_proj_down/<int:is_push>', methods=['GET', 'POST'])
def target_activity_proj_down(is_push):
    result_data = {}
    query = TargetActivityProj.query.all()
    for que in query:
        pid = str(que.project)
        if pid not in result_data:
            result_data[pid] = {}
        basic = json.loads(que.basic)
        localization = json.loads(que.localization)
        task_group = json.loads(que.task_group)

        # 69 消耗x个A 品质的 英雄奖章, 74 累计消耗X个A品质教官升星道具, 76 累计消耗A品质教官专属碎片X个
        special_doc = ['69', '74', '76']
        with open(STATIC_PATH + 'target_task_content.json', encoding='utf-8') as f:
            content = json.load(f)
        task_content = content['task_type']
        detail_content = content['detail_type']

        for array in task_group:
            for node in array:
                node['reward'] = RewardToTMysqlNew(node['reward'])
                node['target_unit'] = node['task_unit']
                node['target'] *= node['target_unit']

                tid_str = str(node['task_type'])
                task_id = node['task_id']

                if task_content[tid_str]['id_flag']:
                    d_type = str(task_content[tid_str]['detail_type'])
                    for detail_node in detail_content[d_type]:
                        if detail_node['id'] == node['detail'][0]:
                            string2_detail_doc = detail_node['detail_doc']
                            break

                for lang_str in range(1, DOC_NUM+1):
                    lang_id = str(lang_str)
                    if 'task_doc' in task_content[tid_str] and lang_id in task_content[tid_str]['task_doc']:
                        cur_doc = task_content[tid_str]['task_doc'][lang_id]
                    else:
                        cur_doc = ''
                    if 'STRING2' in cur_doc:
                        cur_doc = cur_doc.replace('STRING2', string2_detail_doc[lang_id])
                    if 'STRING4' in cur_doc:
                        # 特殊处理69, 74, 76
                        if tid_str in special_doc:
                            if tid_str == '69':
                                for detail_node in detail_content['6']:
                                    if detail_node['id'] == node['detail'][1]:
                                        string4 = detail_node['detail_doc'][lang_id]
                                        cur_doc = cur_doc.replace('STRING4', string4)
                                        break
                            elif tid_str == '74':
                                for detail_node in detail_content['11']:
                                    if detail_node['id'] == node['detail'][1]:
                                        string4 = detail_node['detail_doc'][lang_id]
                                        cur_doc = cur_doc.replace('STRING4', string4)
                                        break
                            elif tid_str == '76':
                                for detail_node in detail_content['12']:
                                    if detail_node['id'] == node['detail'][1]:
                                        string4 = detail_node['detail_doc'][lang_id]
                                        cur_doc = cur_doc.replace('STRING4', string4)
                                        break

                            # cur_doc = cur_doc.replace('STRING4', special_doc[tid_str][str(node['detail'][1])])

                        else:
                            cur_doc = cur_doc.replace('STRING4', str(node['detail'][1]))
                    # if 'STRING1' in cur_doc:
                    #     cur_doc = cur_doc.replace('STRING1', str(node['task_unit']))
                    localization[lang_id]['task_doc'][str(task_id)] = cur_doc

        for i in range(2):
            if len(task_group[-1]) == 0:
                task_group.pop()

        if 'calendar_reward' in basic:
            calendar_reward = RewardToTMysqlNew(basic['calendar_reward'])
        else:
            calendar_reward = []

        if 'calendar_doc_id' not in basic:
            basic['calendar_doc_id'] = 1

        if '_tag' not in basic:
            basic['_tag'] = []

        result_data[pid] = {
            '_tag': basic['_tag'],
            'calendar_conf': {
                'event_type': 63,
                'event_ui': basic['event_ui'],
                'order': 1,
                'jump': 1,
                'localization': {
                    'title': basic['calendar_doc_id'],
                    'info': basic['calendar_doc_id']
                },
                'reward': calendar_reward,
                'show_type': 0
            },
            'basic': {'event_ui': basic['event_ui']},
            'task_refresh': int(basic['task_refresh']),
            'localization': localization,
            'task_group': task_group}

    response = DownLoad('target_activity_proj', result_data, is_push)
    return response

@app.route('/target_activity_tasklist_get_task_type/<int:tid>', methods=['GET'])
def target_activity_tasklist_get_task_type(tid):

    data = TargetActivityList.query.filter_by(id=tid).first()
    task_type = int(data.task_type)

    return jsonify({'task_type': task_type})


@app.route('/target_activity_task_item_action', methods=['POST', 'GET'])
def target_activity_task_item_action():
    update_data = json.loads(request.data)
    taskItemList = update_data['taskItem']

    project_id = int(update_data['project_id'])
    Taskactive = int(update_data['Taskactive'])

    mysql_data = TargetActivityList.query.all()
    task_list = {}
    for data in mysql_data:
        id = str(data.id)
        task_list[id] = data

    task_item_list = []
    for i in range(len(taskItemList)):
        level = int(taskItemList[i]['level'])
        target = int(taskItemList[i]['target'])
        task_unit = int(taskItemList[i]['task_unit'])

        tid = str(taskItemList[i]['tid'])
        tmp_reward = {}
        tmp_reward['0'] = taskItemList[i]['reward']
        reward = RewardToTMysql(tmp_reward)

        task_data = task_list[tid]

        task_type = int(task_data.task_type)
        op_type = int(task_data.op_type)
        detail_id = int(task_data.detail_id)

        detail = [detail_id, level, op_type]

        task_id = int((Taskactive+1)*1000+i)

        tmp = {'detail': detail, 'reward': reward, 'task_unit': task_unit,
               'target': target, 'task_id': task_id, 'task_type': task_type, 'tid': int(tid)}

        task_item_list.append(tmp)

    project_data = TargetActivity.query.filter_by(project=project_id).first()

    task_group = json.loads(project_data.task_group)

    if len(task_group) < Taskactive+1:
        task_group.append(task_item_list)
    else:
        task_group[Taskactive] = task_item_list

    TargetActivity.query.filter_by(project=project_id).update(
        {'task_group': json.dumps(task_group)})

    return jsonify({'msg': '更新成功', 'ret': 0})


@app.route('/strongest_sheriff_score_type_list/', methods=['POST', 'GET'])
def strongest_sheriff_score_type_list():
    with open(STATIC_PATH + 'strongest_sheriff_score_type_list.json', encoding='utf8') as f:
        data = json.load(f)

    result = {}
    task_type_list = data['type_list']

    result['task_type_list'] = data['type_list']

    detail_type_list = {}

    for x in range(len(task_type_list)):
        type = str(task_type_list[x]['value'])
        id_list = task_type_list[x]['id_list']

        if type not in detail_type_list:
            detail_type_list[type] = []

        # 动态生成 chest
        if id_list == 'chest':
            doc_content = loadDocument()
            sub_game_content = loadSubGame()
            if 'sub_game_chest_get_score_config' in sub_game_content:
                chest_id_list = sub_game_content['sub_game_chest_get_score_config']['chest_id_list']
                for chest_id in chest_id_list:
                    if str(chest_id) in doc_content['doc_item']:
                        detail_type_list[type].append({
                            'value': chest_id,
                            'label': doc_content['doc_item'][str(chest_id)]['name']
                            })
                    else:
                        detail_type_list[type].append({
                            'value': chest_id,
                            'label': 'chest error {0}'.format(chest_id)
                            })
        else:
            detail_type_list[type] = data[id_list]

    result['detail_type_list'] = detail_type_list

    result['doc_id_list'] = []
    doc_data = loadDocument()
    for i in doc_data['doc_scoring_rule']:
        result['doc_id_list'].append(
            {"label": doc_data['doc_scoring_rule'][i]['content'], "value": int(i)})

    result['show_list'] = [{"label":"无","value":0},{"label":"满研究","value":1}]
    return jsonify(result)


@app.route('/strongest_sheriff_task_list/', methods=['POST', 'GET'])
def strongest_sheriff_task_list():
    mysql_data = StrongestSheriffTask.query.order_by(
        StrongestSheriffTask.doc_id).all()
    task_list = []
    for p in mysql_data:
        id = int(p.id)
        type = int(p.type)
        id_list = list(map(int, p.id_list.split(",")))
        num = int(p.num)
        score = int(p.score)
        doc_id = int(p.doc_id)
        target_unit = int(p.target_unit)
        show_type = int(p.show_type)

        tmp = {'id': id, 'id_list': id_list, 'num': num,
               'score': score, 'doc_id': doc_id, 'task_type': type, 'target_unit': target_unit, 'show_type': show_type}
        task_list.append(tmp)

    return jsonify(task_list)


@app.route('/strongest_sheriff_task_delete/<int:id>', methods=['GET'])
def strongest_sheriff_task_delete(id):
    project_data = StrongestSheriffTask.query.filter_by(id=id).first()
    db.session.delete(project_data)
    db.session.commit()
    project_data = StrongestSheriffTask.query.filter_by(id=id).first()
    if (project_data is None):
        result = {'msg': '删除成功', 'ret': 0}
    else:
        result = {'msg': '删除失败', 'ret': 1}
    return jsonify(result)


@app.route('/strongest_sheriff_task_action', methods=['POST', 'GET'])
def strongest_sheriff_task_action():

    update_data = json.loads(request.data)

    submit_type = int(update_data['submit_type'])

    task_type = int(update_data['task_type'])
    id_list = update_data['id_list']
    num = int(update_data['num'])
    score = int(update_data['score'])
    doc_id = int(update_data['doc_id'])
    target_unit = int(update_data['target_unit'])
    show_type = int(update_data['show_type'])

    if submit_type == 0:
        mysql_data = StrongestSheriffTask(
            id_list=id_list, score=score, num=num, doc_id=doc_id, type=task_type, target_unit=target_unit, show_type=show_type)
        db.session.add(mysql_data)
        db.session.commit()
        id = mysql_data.id
    else:
        StrongestSheriffTask.query.filter_by(id=update_data['id']).update(
            {'type': task_type, 'id_list': id_list, 'score': score, 'num': num, 'doc_id': doc_id, 'target_unit': target_unit, 'show_type': show_type})
        db.session.commit()
        id = update_data['id']

    return jsonify({'msg': '更新成功', 'ret': 0, 'id': id})


@app.route('/target_activity_task_list/', methods=['POST', 'GET'])
def target_activity_task_list():
    mysql_data = TargetActivityList.query.all()
    task_list = []
    for p in mysql_data:
        id = int(p.id)
        task_type = int(p.task_type)
        detail_type = int(p.detail_type)
        detail_id = int(p.detail_id)
        tmp = {'id': id, 'task_type': task_type,
               'detail_type': detail_type, 'detail_id': detail_id}
        task_list.append(tmp)

    task_id_list = {}

    with open(STATIC_PATH + 'target_activity_task_type_list.json', encoding='utf8') as f:
        task_id_list = json.load(f)

    return jsonify({'task_list': task_list, 'task_id_list': task_id_list['detail_id']})


@app.route('/target_activity_task_type_list/', methods=['POST', 'GET'])
def target_activity_task_type_list():
    task_id_list = {}
    with open(STATIC_PATH + 'target_activity_task_type_list.json', encoding='utf8') as f:
        task_id_list = json.load(f)
    result = []
    data = task_id_list['task']
    for task_type in data:
        tmp = {"label": data[task_type]['name'], "value": int(task_type)}
        result.append(tmp)

    return jsonify(result)


@app.route('/target_activity_task_delete/<int:id>', methods=['GET'])
def target_activity_task_delete(id):
    project_data = TargetActivityList.query.filter_by(id=id).first()
    db.session.delete(project_data)
    db.session.commit()
    project_data = TargetActivityList.query.filter_by(id=id).first()
    if (project_data is None):
        result = {'msg': '删除成功', 'ret': 0}
    else:
        result = {'msg': '删除失败', 'ret': 1}
    return jsonify(result)


@app.route('/target_activity_task_action', methods=['POST', 'GET'])
def target_activity_task_action():

    update_data = json.loads(request.data)

    task_type_list = {}
    with open(STATIC_PATH + 'target_activity_task_type_list.json', encoding='utf8') as f:
        task_type_list = json.load(f)

    for node in update_data['task_list']:
        task_type = int(node['task_type'])
        detail_type = int(node['detail_type'])
        detail_id = int(node['detail_id'])
        id = int(node['id'])
        op_type = int(task_type_list['task'][str(task_type)]['op_type'])
        name = task_type_list['task'][str(task_type)]['name']
        if detail_type == 0 or detail_type == 3:
            label = name
        elif detail_type == 1:
            doc_data = loadDocument()
            label = name + '--' + doc_data['doc_building'][str(detail_id)]['name']
        elif detail_type == 2:
            doc_data = loadDocument()
            label = name + '--' + doc_data['doc_troop'][str(detail_id)]['name']
        elif detail_type == 4:
            doc_data = loadDocument()
            label = name + '--' + doc_data['doc_resource'][str(detail_id)]['name']
        if id == -1:
            mysql_data = TargetActivityList(
                task_type=task_type, op_type=op_type, detail_type=detail_type, detail_id=detail_id, label=label)
            db.session.add(mysql_data)
        else:
            TargetActivityList.query.filter_by(id=id).update(
                {'task_type': task_type, 'detail_id': detail_id, 'detail_type': detail_type, 'op_type': op_type, 'label': label})
        db.session.commit()

    return jsonify({'msg': '更新成功', 'ret': 0})


@app.route('/down_target_activity/<int:is_push>', methods=['GET', 'POST'])
def down_target_activity(is_push):

    result_data = {}
    project_data = TargetActivity.query.all()
    for p in project_data:
        project_id = str(p.project)
        task_group = json.loads(p.task_group)
        basic = json.loads(p.basic)

        new_task_group = []
        for x in range(len(task_group)):
            if len(task_group[x]) > 0:
                new_task_group.append(task_group[x])

        result_data[project_id] = {}
        result_data[project_id]['basic'] = {}
        result_data[project_id]['basic']['event_ui'] = int(basic['event_ui'])
        result_data[project_id]['localization'] = basic['localization']
        result_data[project_id]['task_refresh'] = int(basic['task_refresh'])
        result_data[project_id]['task_group'] = new_task_group

    response = DownLoad('target_activity_proj', result_data, is_push)

    return response


@app.route('/monument_index', methods=['GET'])
def monument_index():
    data = Monument.query.all()
    result = []
    for d in data:
        # 20220812 增加 remark
        remark = d.remark
        project = int(d.project)
        localization = json.loads(d.localization)
        title = localization['1']['0']['title']
        tmp = {"project": project, "title": title, 'remark': remark}
        result.append(tmp)
    return jsonify(result)

@app.route('/update_monument_remark', methods=['GET', 'POST'])
def update_monument_remark():
    update_data = json.loads(request.data)
    pid = update_data['project']
    remark = update_data['remark']

    project_data = Monument.query.filter_by(project=pid).first()
    project_data.remark = remark
    db.session.commit()
    return jsonify({'ret': 0, 'msg': '更新remark成功'})

@app.route('/monument_task_list', methods=['GET'])
def monument_task_list():

    TaskList = MonumentTask.query.all()
    all_task_list = {}
    for p in TaskList:
        id = str(p.id)
        all_task_list[id] = p
    return jsonify(all_task_list)


@app.route('/monument_reward/<field>/<int:tid>', methods=['GET'])
def monument_reward(field, tid):
    pid = session['pid']

    project_data = Monument.query.filter_by(project=pid).first()

    tasks = json.loads(project_data.tasks)

    result_bonus = {}
    for i in range(len(tasks)):
        task_id = int(tasks[i]['task_id'])

        if task_id == int(tid):

            if field == 'rank_reward':
                reward_data = tasks[i]['rank_reward']
                if len(reward_data) > 0:

                    reward = rewardList()
                    reward = reward['name']
                    for idx in range(len(reward_data)):

                        _from = reward_data[idx]['from']
                        _to = reward_data[idx]['to']
                        a_reward = reward_data[idx]['reward']

                        for i in range(len(a_reward)):
                            item_type = a_reward[i]['a'][0]
                            item_id = a_reward[i]['a'][1]
                            item_num = a_reward[i]['a'][2]
                            item_rate = 1
                            item_price = 100
                            item_pos = idx
                            if item_type in reward and str(item_id) in reward[item_type]:
                                item_name = reward[item_type][str(item_id)]
                            else:
                                item_name = 'ERROR'

                            if item_pos not in result_bonus:
                                result_bonus[item_pos] = {}
                                result_bonus[item_pos]['from'] = _from
                                result_bonus[item_pos]['to'] = _to
                                result_bonus[item_pos]['reward'] = []

                            tmp = {"type": item_type, "id": item_id, "num": item_num, "rate": item_rate,
                                   "price": item_price, "pos": item_pos, "name": item_name, "from": _from, "to": _to}

                            result_bonus[item_pos]['reward'].append(tmp)
            elif field == 'special_reward':
                result_bonus = tasks[i]['special_reward']
            else:
                result_bonus = []

        result = {'project': project_data.project, 'bonus': result_bonus}

    return jsonify(result)


@app.route('/monument_basic/<field>/<int:pid>', methods=['GET'])
def monument_basic(field, pid=0):
    if pid != 0:
        session['pid'] = pid
    pid = session['pid']

    project_data = Monument.query.filter_by(project=pid).first()
    if (project_data is None):
        result = {'msg': '找不到数据'}
    else:
        if field == 'basic':
            result = {}
            tasks = json.loads(project_data.tasks)

            for x in range(len(tasks)):
                if x == 0 and '_tag' not in tasks[x]:
                    tasks[x]['_tag'] = []
                tasks[x]['rank_reward_num'] = len(tasks[x]['rank_reward'])
                tasks[x]['special_reward_num'] = len(
                    tasks[x]['special_reward'])

            Task_data = MonumentTask.query.all()
            task_list = []
            task_id_list = {}
            for d in Task_data:
                tmp = {"label": str(d.name), "value": int(d.id)}
                task_list.append(tmp)
                id = int(d.id)
                type = int(d.type)
                name = str(d.name)
                task_class = int(d.task_class)
                task_num = int(d.task_num)
                task_level = int(d.task_level)
                target = int(d.target)
                rank_type = int(d.rank_type)
                op_type = int(d.op_type)
                has_rank = int(d.has_rank)

                task_id_list[id] = {'type': type, 'name': name, 'task_class': task_class, 'task_num': task_num,
                                    'task_level': task_level, 'target': target, 'rank_type': rank_type, 'op_type': op_type, 'has_rank': has_rank}

            result['tasks'] = tasks
            result['task_list'] = task_list
            result['task_id_list'] = task_id_list
            result['project'] = project_data.project

        elif field == 'delete':
            project_data = Monument.query.filter_by(project=pid).first()
            db.session.delete(project_data)
            db.session.commit()
            project_data = Monument.query.filter_by(project=pid).first()
            if (project_data is None):
                result = {'msg': '删除成功', 'ret': 0}
            else:
                result = {'msg': '删除失败', 'ret': 1}

        elif field == 'clone':
            result = {'msg': '添加成功', 'ret': 0}
            new_project_data = Monument(
                localization=project_data.localization,
                tasks=project_data.tasks,
                remark=project_data.remark)
            db.session.add(new_project_data)
            db.session.commit()

            project_id = new_project_data.project
            if (project_id is None):
                result = {'msg': '添加失败', 'ret': 2}

    return jsonify(result)


@app.route('/update_monument_task', methods=['GET', 'POST'])
def update_monument_task():

    update_data = json.loads(request.data)
    project_id = session['pid']

    update_type = update_data['update_type']

    update_data.pop('update_type')

    if update_type == 'task':
        data = update_data['data']
        castle_lv = int(update_data['castle_lv'])
        _tag = update_data['_tag']

        sql_data = []

        for i in range(len(data)):
            task_id = i
            has_rank = int(data[i]['has_rank'])
            rank_type = int(data[i]['rank_type'])
            task_time = int(data[i]['task_time'])
            task_class = int(data[i]['task_class'])
            reward_size = int(data[i]['reward_size'])
            rank_show_size = int(data[i]['rank_show_size'])
            need_settlement = int(data[i]['need_settlement'])
            castle_lv = castle_lv
            event_ui = int(data[i]['event_ui'])
            rank_reward = data[i]['rank_reward']
            special_reward = data[i]['special_reward']

            for s in range(len(special_reward)):
                special_reward[s]['type'] = int(special_reward[s]['type'])

                if int(special_reward[s]['type']) == 1 or int(special_reward[s]['type']) == 2:
                    special_reward[s]['id'] = -1
                else:
                    special_reward[s]['id'] = int(special_reward[s]['id'])

                if int(special_reward[s]['type']) == 0:
                    special_reward[s]['num'] = 0
                else:
                    special_reward[s]['num'] = int(special_reward[s]['num'])

                special_reward[s]['unlock_type'] = int(
                    special_reward[s]['unlock_type'])
                special_reward[s]['unlock_data'] = list(
                    map(int, special_reward[s]['unlock_data']))

            detail = list(map(int, data[i]['detail']))
            id = int(data[i]['id'])

            sql_data.append({
                "id": id, "need_settlement": need_settlement,
                "reward_size": reward_size, "rank_show_size": rank_show_size,
                "task_id": task_id, "has_rank": has_rank, "rank_type": rank_type,
                "task_time": task_time, "task_class": task_class,
                "castle_lv": castle_lv, "rank_reward": rank_reward,
                "special_reward": special_reward, "detail": detail,
                "event_ui": event_ui, '_tag': _tag})
            Monument.query.filter_by(project=project_id).update(
                {'tasks': json.dumps(sql_data)})

    elif update_type == 'rank_reward':
        task_id = update_data['task_id']
        bonus_list = update_data['bonus']

        rank_reward_data = []

        for idx in bonus_list:
            data = bonus_list[idx]
            _from = int(data['from'])
            _to = int(data['to'])
            reward = []
            for r_idx in range(len(data['reward'])):
                item_type = int(data['reward'][r_idx]['type'])
                item_id = int(data['reward'][r_idx]['id'])
                item_num = int(data['reward'][r_idx]['num'])
                tmp = {}
                tmp['a'] = [item_type, item_id, item_num]
                reward.append(tmp)

            rank_reward_data.append(
                {"from": _from, "to": _to, "reward": reward})

        project_data = Monument.query.filter_by(project=project_id).first()

        task_data = json.loads(project_data.tasks)

        for i in range(len(task_data)):
            if int(task_data[i]['task_id']) == int(task_id):
                task_data[i]['rank_reward'] = rank_reward_data

        Monument.query.filter_by(project=project_id).update(
            {'tasks': json.dumps(task_data)})

    db.session.commit()
    return jsonify({'msg': '更新成功', 'ret': 0})


@app.route('/down_monument/<int:is_push>', methods=['GET', 'POST'])
def down_monument(is_push):

    result_data = {}
    project_data = Monument.query.all()
    for p in project_data:
        project_id = str(p.project)
        localization = json.loads(p.localization)
        tasks = json.loads(p.tasks)

        _tag = tasks[0]['_tag'] if '_tag' in tasks[0] else []
        for i in range(len(tasks)):
            node = tasks[i]
            if '_tag' in node:
                del node['_tag']

        result_data[project_id] = {}
        result_data[project_id]['tasks'] = tasks
        result_data[project_id]['localization'] = localization
        result_data[project_id]['min_castle_lv'] = tasks[0]['castle_lv']
        result_data[project_id]['_tag'] = _tag

    response = DownLoad('monument_proj', result_data, is_push)

    return response


@app.route('/mysterious_merchant_index', methods=['GET'])
def mysterious_merchant_index():
    data = MysteriousMerchant.query.all()
    result = []
    for d in data:
        project = int(d.project)
        # info = json.loads(d.basic)
        # title = info['localization']['1']['title']
        tmp = {"project": project, "title": ''}
        result.append(tmp)
    return jsonify(result)


@app.route('/mysterious_merchant_basic/<field>/<int:pid>', methods=['GET'])
def mysterious_merchant_basic(field, pid=0):
    if pid != 0:
        session['pid'] = pid
    pid = session['pid']

    project_data = MysteriousMerchant.query.filter_by(project=pid).first()
    if (project_data is None):
        result = {'msg': '找不到数据'}
    else:
        if field == 'basic':
            result = {}
            basic = json.loads(project_data.basic)
            basic['a'][2] = fomat_timestamp(basic['a'][2], "%Y-%m-%d %H:%M:%S")
            result['basic'] = basic
            result['project'] = project_data.project

        elif field == 'delete':
            project_data = MysteriousMerchant.query.filter_by(
                project=pid).first()
            db.session.delete(project_data)
            db.session.commit()
            project_data = MysteriousMerchant.query.filter_by(
                project=pid).first()
            if (project_data is None):
                result = {'msg': '删除成功', 'ret': 0}
            else:
                result = {'msg': '删除失败', 'ret': 1}

        elif field == 'clone':
            result = {'msg': '添加成功', 'ret': 0}
            new_project_data = MysteriousMerchant(
                basic=project_data.basic, goods=project_data.goods)
            db.session.add(new_project_data)
            db.session.commit()

            project_id = new_project_data.project
            if (project_id is None):
                result = {'msg': '添加失败', 'ret': 2}

            result = {'project': project_data.project, 'bonus': result_bonus}
    return jsonify(result)


@app.route('/update_mysterious_merchant', methods=['GET', 'POST'])
def update_mysterious_merchant():

    update_data = json.loads(request.data)
    project_id = session['pid']

    update_type = update_data['update_type']
    project_id = update_data['project']

    if 'project' in update_data:
        update_data.pop('project')

    update_data.pop('update_type')

    sql_data = json.dumps(update_data)

    if update_type == 'basic':
        basic = update_data['basic']

        refresh_gem_cost_str = basic['refresh_gem_cost'].split(',')
        refresh_probability_str = basic['refresh_probability'].split(',')
        basic['refresh_gem_cost'] = []
        basic['refresh_probability'] = []

        for x in range(len(refresh_gem_cost_str)):
            basic['refresh_gem_cost'].append(int(refresh_gem_cost_str[x]))
        for x in range(len(refresh_probability_str)):
            basic['refresh_probability'].append(
                int(refresh_probability_str[x]))

        basic['a'][2] = fomat_date_str(basic['a'][2])
        sql_data = json.dumps(basic)
        MysteriousMerchant.query.filter_by(
            project=project_id).update({'basic': sql_data})

    db.session.commit()
    return jsonify({'msg': '更新成功', 'ret': 0})


@app.route('/mysterious_merchant_goods/<int:goods_type>/<item_type>', methods=['GET'])
def mysterious_merchant_goods(goods_type, item_type):
    pid = session['pid']

    project_data = MysteriousMerchant.query.filter_by(project=pid).first()
    result = {}
    data = json.loads(project_data.goods)

    if str(item_type) == '-1':
        goods_list = data[int(goods_type)]
    elif str(item_type) == "-2":
        item_list = data[int(goods_type)]['item']
        level_list = []
        for x in item_list:
            level_list.append(int(x))
        level_list.sort()
        goods_list = []
        for x in range(len(level_list)):
            if x < len(level_list) - 1:
                label = str(level_list[x]) + '-' + str(level_list[x+1]-1)
            else:
                label = str(level_list[x])
            value = str(level_list[x])
            tmp = {"label": label, "value": value}
            goods_list.append(tmp)
    else:

        reward = rewardList()
        reward = reward['name']

        json_data = data[int(goods_type)]['item'][str(item_type)]
        goods_list = []

        for i in json_data:
            tmp = {}
            tmp['id'] = i
            tmp['a'] = json_data[i]['a']
            tmp['cost'] = json_data[i]['cost']
            cost_type = tmp['cost'][0]
            cost_id = tmp['cost'][1]
            cost_name = reward[cost_type][str(cost_id)]
            tmp['cost'].append(cost_name)

            item_type = json_data[i]['reward']['a'][0]
            item_id = json_data[i]['reward']['a'][1]
            item_num = json_data[i]['reward']['a'][2]
            item_name = reward[item_type][str(item_id)]
            tmp['item'] = [item_type, item_id, item_num, item_name]

            goods_list.append(tmp)

    result['goods_list'] = goods_list
    result['project'] = project_data.project

    return jsonify(result)


@app.route('/update_mysterious_merchant_goods', methods=['POST', 'GET'])
def update_mysterious_merchant_goods():
    json_data = json.loads(request.data)

    project_id = session['pid']
    data = json_data['data']
    castle_lv = str(json_data['castle_lv'])
    goods_type = int(json_data['goods_type'])

    update_data = {}

    for i in range(len(data)):
        # id = str(i)+"_"+str(castle_lv)
        id = str(int(i) * 100 + int(castle_lv))
        a = data[i]['a']
        cost = data[i]['cost']
        sale = (1-round(int(cost[3])/int(cost[2]), 2))*10000
        cost[4] = round(sale)
        del cost[5]
        cost = list(map(int, cost))
        item = data[i]['item']
        reward = {'a': [int(item[0]), int(item[1]), int(item[2])]}

        update_data[id] = {'a': a, 'cost': cost, 'reward': reward}

    mysql_data = MysteriousMerchant.query.filter_by(project=project_id).first()
    project_data = json.loads(mysql_data.goods)

    project_data[goods_type]['item'][castle_lv] = update_data

    MysteriousMerchant.query.filter_by(project=project_id).update(
        {'goods': json.dumps(project_data)})

    return jsonify({'msg': '更新成功', 'ret': 0})


@app.route('/mysterious_merchant_action', methods=['POST', 'GET'])
def mysterious_merchant_action():
    json_data = json.loads(request.data)

    project_id = session['pid']
    update_data = json_data['data']
    level = int(json_data['level'])

    mysql_data = MysteriousMerchant.query.filter_by(project=project_id).first()
    project_data = json.loads(mysql_data.goods)

    project_data[level]['a'] = update_data['a']
    project_data[level]['r'] = update_data['r']

    MysteriousMerchant.query.filter_by(project=project_id).update(
        {'goods': json.dumps(project_data)})

    return jsonify({'msg': '更新成功', 'ret': 0})


@app.route('/require_list', methods=['GET'])
def require_list():
    result_data = {"7": [], "8": [], "9": [], "21": []}
    doc_data = loadDocument()
    for x in doc_data['doc_building']:
        # id = int(doc_data['doc_building'][x]['id'])
        name = doc_data['doc_building'][x]['name']
        tmp = {"label": name, "value": int(x)}
        result_data["7"].append(tmp)

    for x in doc_data['doc_research']:
        # id = int(doc_data['doc_research'][x]['id'])
        name = doc_data['doc_research'][x]['name']
        tmp = {"label": name, "value": int(x)}
        result_data["8"].append(tmp)

    result_data["9"].append({"label": '默认', "value": 0})
    result_data["21"].append({"label": '默认', "value": 0})

    name_list = [{"label": "建筑", "value": 7}, {"label": "研究", "value": 8}, {
        "label": "领主等级", "value": 9}, {"label": "龙技能等级", "value": 21}]
    result = {}
    result['list'] = result_data
    result['name'] = name_list
    return jsonify(result)


@app.route('/down_mysterious_merchant/<int:is_push>', methods=['GET', 'POST'])
def down_mysterious_merchant(is_push):
    result_data = {}
    project_data = MysteriousMerchant.query.all()
    for p in project_data:
        project_id = str(p.project)
        basic = json.loads(p.basic)
        goods = json.loads(p.goods)

        result_data[project_id] = {}
        result_data[project_id] = basic
        result_data[project_id]['goods'] = goods

    response = DownLoad('mysterious_merchant_project', result_data, is_push)

    return response


@app.route('/continuous_activities_index', methods=['GET'])
def continuous_activities_index():
    data = ContinuousActivities.query.all()
    result = []
    for d in data:
        project = int(d.project)
        info = json.loads(d.basic)
        if 'localization' in info and '1' in info['localization']:
            title = info['localization']['1']['title']
        else:
            title = ''
        tmp = {"project": project, "title": title}
        result.append(tmp)
    return jsonify(result)

@app.route('/clone_continuous_activities/<int:pid>', methods=['GET'])
def clone_continuous_activities(pid):
    result = {'msg': '添加成功', 'ret': 0}
    project_data = ContinuousActivities.query.filter_by(project=pid).first()
    if (project_data is None):
        result = {'msg': '找不到数据', 'ret': 1}
    else:
        new_project_data = ContinuousActivities(basic=project_data.basic, task_group=project_data.task_group,
                                                task_chest_reward=project_data.task_chest_reward, top_reward=project_data.top_reward)
        db.session.add(new_project_data)
        db.session.commit()

        project_id = new_project_data.project

        if (project_id is None):
            result = {'msg': '添加失败', 'ret': 2}

    return jsonify(result)


@app.route('/delete_continuous_activities/<int:pid>', methods=['GET'])
def delete_continuous_activities(pid):

    # db.session.query(db.ContinuousActivities).filter_by(project=pid).first()

    project_data = ContinuousActivities.query.filter_by(project=pid).first()
    db.session.delete(project_data)
    db.session.commit()

    project_data = ContinuousActivities.query.filter_by(project=pid).first()
    if (project_data is None):
        result = {'msg': '删除成功', 'ret': 0}
    else:
        result = {'msg': '删除失败', 'ret': 1}

    return jsonify(result)


@app.route('/down_continuous_activities/<int:is_push>', methods=['GET', 'POST'])
def down_continuous_activities(is_push):
    result_data = {}
    project_data = ContinuousActivities.query.all()
    for p in project_data:
        project_id = str(p.project)
        basic = json.loads(p.basic)
        task_group = json.loads(p.task_group)
        task_chest_reward = json.loads(p.task_chest_reward)

        result_data[project_id] = {}
        result_data[project_id]['basic'] = {}
        result_data[project_id]['basic']['event_ui'] = int(basic['event_ui'])
        result_data[project_id]['top_reward'] = json.loads(p.top_reward)

        result_data[project_id]['localization'] = {}

        localization = json.dumps(basic['localization'])

        localization = localization.replace('#-n-#', '\\n')

        result_data[project_id]['localization'] = json.loads(localization)

        result_data[project_id]['first_day_mode'] = int(
            basic['first_day_mode'])
        result_data[project_id]['activity_day'] = int(basic['activity_day'])
        result_data[project_id]['task_day'] = int(basic['task_day'])
        result_data[project_id]['show_time'] = int(basic['show_time'])

        result_data[project_id]['task_chest_reward'] = task_chest_reward

        result_data[project_id]['task_num'] = 0

        for g in range(len(task_group)):
            task_list = task_group[g]['task']
            for t in range(len(task_list)):
                result_data[project_id]['task_num'] += len(
                    task_list[t]['task_item'])

        copy_task_group = copy.deepcopy(task_group)

        for d in result_data[project_id]['localization']:
            new_task_group = copy.deepcopy(copy_task_group)
            for x in range(len(new_task_group)):
                task_list = new_task_group[x]['task']

                new_task_group[x]['theme'] = new_task_group[x]['doc'][d]
                del new_task_group[x]['doc']

                if 'doc' in task_group[x]:
                    del task_group[x]['doc']
                if 'theme' in task_group[x]:
                    del task_group[x]['theme']

                for s in range(len(task_list)):
                    task_item_list = task_list[s]['task_item']

                    new_task_group[x]['task'][s]['sub_theme'] = new_task_group[x]['task'][s]['doc'][d]
                    del new_task_group[x]['task'][s]['doc']

                    if 'doc' in task_group[x]['task'][s]:
                        del task_group[x]['task'][s]['doc']

                    if 'sub_theme' in task_group[x]['task'][s]:
                        del task_group[x]['task'][s]['sub_theme']

                    if 'tid' in task_group[x]['task'][s]:
                        del task_group[x]['task'][s]['tid']

                    for i in range(len(task_item_list)):
                        if 'doc' not in task_item_list[i]:
                            print("##"+str(project_id)+"#####"+str(x) +
                                  "#######"+str(s)+"#######"+str(i))
                        doc = task_item_list[i]['doc']

                        new_task_group[x]['task'][s]['task_item'][i] = {}

                        if 'doc' in task_group[x]['task'][s]['task_item'][i]:
                            del task_group[x]['task'][s]['task_item'][i]['doc']

                        if d in doc:
                            new_task_group[x]['task'][s]['task_item'][i]['doc'] = doc[d]
                        else:
                            new_task_group[x]['task'][s]['task_item'][i]['doc'] = doc["1"]

            result_data[project_id]['localization'][d]['task_group'] = new_task_group

        result_data[project_id]['task_group'] = task_group

    response = DownLoad('continuous_activities_proj', result_data, is_push)

    return response


@app.route('/update_continuous_activities', methods=['GET', 'POST'])
def update_continuous_activities():

    update_data = json.loads(request.data)

    update_type = update_data['update_type']
    project_id = update_data['project']

    update_data.pop('project')
    update_data.pop('update_type')

    sql_data = json.dumps(update_data)

    if update_type == 'basic':
        sql_data = json.dumps(update_data)
        ContinuousActivities.query.filter_by(
            project=project_id).update({'basic': sql_data})
    elif update_type == 'task_chest_reward':

        task_chest_reward = RewardToTMysql(update_data['task_chest_reward'])
        top_reward = RewardToTMysql(update_data['top_reward'])

        ContinuousActivities.query.filter_by(project=project_id).update(
            {'task_chest_reward': json.dumps(task_chest_reward), 'top_reward': json.dumps(top_reward)})

    db.session.commit()
    return jsonify({'msg': '更新成功', 'ret': 0})


@app.route('/continuous_activities_basic/<field>/<int:pid>', methods=['GET'])
def continuous_activities_basic(field, pid=0):

    if pid == 0:
        return jsonify({"ret":1,"msg":'pid不合法'})
    project_data = ContinuousActivities.query.filter_by(project=pid).first()
    if (project_data is None):
        result = {'msg': '找不到数据'}
    else:
        if field == 'basic':
            result = json.loads(project_data.basic)
            task_group = json.loads(project_data.task_group)
            result['task_num'] = 0
            for x in range(len(task_group)):
                for i in range(len(task_group[x]['task'])):
                    result['task_num'] += len(task_group[x]['task'][i]['task_item'])
            result['project'] = project_data.project

        elif field == 'task_group':
            result = {}
            task_group = json.loads(project_data.task_group)
            data = []
            for idx in range(len(task_group)):
                theme = task_group[idx]['theme']
                tmp = {'id': idx, 'theme': theme}
                data.append(tmp)

            result['task_group'] = data
            result['project'] = project_data.project
        elif field == 'task_chest_reward':

            task_chest_reward = json.loads(project_data.task_chest_reward)
            top_reward = json.loads(project_data.top_reward)
            result = {'project': project_data.project, 'task_chest_reward': RewardToDic(
                task_chest_reward), 'top_reward': RewardToDic(top_reward)}
    return jsonify(result)


@app.route('/continuous_task/<int:day>/<int:task>/<int:pid>', methods=['GET'])
def continuous_task(day, task, pid):
    project_data = ContinuousActivities.query.filter_by(project=pid).first()
    result = {}
    task_group = json.loads(project_data.task_group)
    task_item = task_group[day]['task'][task]['task_item']

    reward_item_list = rewardList()
    reward_item_list = reward_item_list['name']

    task_item_list = []
    for i in range(len(task_item)):
        item = task_item[i]
        level = item['detail'][1]
        task_type = item['task_type']
        tid = item['tid']
        target = item['target']
        if 'task_guide' not in item:
            task_guide = 0
        else:
            task_guide = item['task_guide']

        reward = RewardToDic(item['reward'],0,reward_item_list)

        tmp = {'level': level, 'task_type': task_type, 'tid': tid,
               'reward': reward[0], 'target': target, 'LevelActive': False, 'task_guide': task_guide}
        task_item_list.append(tmp)

    TaskList = ContinuousTaskList.query.all()
    all_task_list = []
    for p in TaskList:
        id = int(p.id)
        label = p.label
        tmp = {"value": id, "label": label}
        all_task_list.append(tmp)

    result['all_task_list'] = all_task_list
    result['task_item_list'] = task_item_list
    result['project'] = project_data.project

    return jsonify(result)


@app.route('/continuous_tasklist_get_task_type/<int:tid>', methods=['GET'])
def continuous_tasklist_get_task_type(tid):

    data = ContinuousTaskList.query.filter_by(id=tid).first()
    task_type = int(data.task_type)

    return jsonify({'task_type': task_type})


@app.route('/continuous_task_item_action', methods=['POST', 'GET'])
def continuous_task_item_action():
    update_data = json.loads(request.data)

    # print(update_data)
    taskItemList = update_data['taskItem']

    project_id = int(update_data['project_id'])
    Dayactive = int(update_data['Dayactive'])
    Taskactive = int(update_data['Taskactive'])

    mysql_data = ContinuousTaskList.query.all()
    task_list = {}
    for data in mysql_data:
        id = str(data.id)
        task_list[id] = data

    task_item_list = []
    for i in range(len(taskItemList)):
        level = int(taskItemList[i]['level'])
        target = int(taskItemList[i]['target'])
        tid = str(taskItemList[i]['tid'])
        task_guide = int(taskItemList[i]['task_guide'])
        tmp_reward = {}
        tmp_reward['0'] = taskItemList[i]['reward']
        reward = RewardToTMysql(tmp_reward)

        task_data = task_list[tid]

        task_type = int(task_data.task_type)
        op_type = int(task_data.op_type)
        detail_id = int(task_data.detail_id)

        detail = [detail_id, level, op_type]
        task_id = str(Dayactive) + '_' + str(Taskactive) + '_' + str(i)
        tmp = {'detail': detail, 'reward': reward, 'target': target, 'task_id': task_id,
               'task_type': task_type, 'tid': int(tid), 'task_guide': task_guide}

        task_item_list.append(tmp)

    project_data = ContinuousActivities.query.filter_by(
        project=project_id).first()

    task_group = json.loads(project_data.task_group)

    task_group[Dayactive]['task'][Taskactive]['task_item'] = task_item_list

    ContinuousActivities.query.filter_by(project=project_id).update(
        {'task_group': json.dumps(task_group)})

    return jsonify({'msg': '更新成功', 'ret': 0})


@app.route('/continuous_task_list/', methods=['POST', 'GET'])
def continuous_task_list():
    mysql_data = ContinuousTaskList.query.all()
    task_list = []
    for p in mysql_data:
        id = int(p.id)
        task_type = int(p.task_type)
        detail_type = int(p.detail_type)
        detail_id = int(p.detail_id)
        tmp = {'id': id, 'task_type': task_type,
               'detail_type': detail_type, 'detail_id': detail_id}
        task_list.append(tmp)

    task_id_list = {}

    with open(STATIC_PATH + 'continue_task_type_list.json', encoding='utf8') as f:
        task_id_list = json.load(f)

    return jsonify({'task_list': task_list, 'task_id_list': task_id_list['detail_id']})


@app.route('/continuous_task_type_list/', methods=['POST', 'GET'])
def continuous_task_type_list():
    task_id_list = {}
    with open(STATIC_PATH + 'continue_task_type_list.json', encoding='utf8') as f:
        task_id_list = json.load(f)
    result = []
    data = task_id_list['task']
    for task_type in data:
        tmp = {"label": data[task_type]['name'], "value": int(task_type)}
        result.append(tmp)

    return jsonify(result)


@app.route('/continuous_task_action', methods=['POST', 'GET'])
def continuous_task_action():

    update_data = json.loads(request.data)

    submit_type = int(update_data['submit_type'])
    task_type = int(update_data['task_type'])
    detail_id = int(update_data['detail_id'])
    detail_type = int(update_data['detail_type'])

    task_type_list = {}
    with open(STATIC_PATH + 'continue_task_type_list.json', encoding='utf8') as f:
        task_type_list = json.load(f)

    op_type = int(task_type_list['task'][str(task_type)]['op_type'])

    name = task_type_list['task'][str(task_type)]['name']

    if detail_type == 0 or detail_type == 3:
        label = name
    elif detail_type == 1:
        doc_data = loadDocument()
        label = name + '--' + doc_data['doc_building'][str(detail_id)]['name']
    elif detail_type == 2:
        doc_data = loadDocument()
        label = name + '--' + doc_data['doc_troop'][str(detail_id)]['name']
    elif detail_type == 4:
        doc_data = loadDocument()
        label = name + '--' + doc_data['doc_resource'][str(detail_id)]['name']

    if submit_type == 0:
        mysql_data = ContinuousTaskList(
            task_type=task_type, op_type=op_type, detail_type=detail_type, detail_id=detail_id, label=label)
        db.session.add(mysql_data)
    else:
        ContinuousTaskList.query.filter_by(id=update_data['id']).update(
            {'task_type': task_type, 'detail_id': detail_id, 'detail_type': detail_type, 'op_type': op_type, 'label': label})
    db.session.commit()

    return jsonify({'msg': '更新成功', 'ret': 0})


@app.route('/novice_recharge_index', methods=['GET'])
def novice_recharge_index():
    data = NoviceRecharge.query.all()
    result = []
    for d in data:
        project = int(d.project)
        info = json.loads(d.basic)
        title = info['localization']['1']['content'][0]
        tmp = {"project": project, "title": title}
        result.append(tmp)
    return jsonify(result)


@app.route('/update_novice_recharge', methods=['GET', 'POST'])
def update_novice_recharge():

    update_data = json.loads(request.data)
    project_id = session['pid']

    update_type = update_data['update_type']
    project_id = update_data['project']

    if 'project' in update_data:
        update_data.pop('project')
    update_data.pop('update_type')

    if update_type == 'localization':

        project_data = NoviceRecharge.query.filter_by(
            project=project_id).first()

        basic = json.loads(project_data.basic)

        content = update_data['content']
        doc_id = str(update_data['doc_id'])
        idx = int(update_data['id'])

        basic['localization'][doc_id]['content'][idx] = content

        NoviceRecharge.query.filter_by(project=project_id).update({
            'basic': json.dumps(basic)})

    elif update_type == 'novice_recharge':
        rank_reward_data = []
        bonus_list = update_data['bonus']
        for idx in bonus_list:
            data = bonus_list[idx]
            total_value = int(data['total_value'])
            event_ui = int(data['event_ui'])
            score = int(data['score'])
            reward = []
            for r_idx in range(len(data['reward'])):
                item_type = int(data['reward'][r_idx]['type'])
                item_id = int(data['reward'][r_idx]['id'])
                item_num = int(data['reward'][r_idx]['num'])
                tmp = {}
                tmp['a'] = [item_type, item_id, item_num]
                reward.append(tmp)

            rank_reward_data.append(
                {"total_value": total_value, "event_ui": event_ui, "score": score, "reward": reward})

        NoviceRecharge.query.filter_by(project=project_id).update(
            {'goal_list': json.dumps(rank_reward_data)})

    db.session.commit()
    return jsonify({'msg': '更新成功', 'ret': 0})


@app.route('/novice_recharge_basic/<field>/<int:pid>', methods=['GET'])
def novice_recharge_basic(field, pid=0):
    if pid != 0:
        session['pid'] = pid
    pid = session['pid']
    project_data = NoviceRecharge.query.filter_by(project=pid).first()
    if (project_data is None):
        result = {'msg': '找不到数据'}
    else:
        if field == 'basic':
            result = {}
            basic = json.loads(project_data.basic)
            goal_list = json.loads(project_data.goal_list)

            content_list = {}
            for doc_id in basic['localization']:
                if doc_id not in content_list:
                    content_list[doc_id] = []
                for goal_idx in range(len(basic['localization'][doc_id]['content'])):

                    goal = goal_list[goal_idx]['score']

                    content = basic['localization'][doc_id]['content'][goal_idx]

                    tmp = {"id": goal_idx, 'goal': goal, 'content': content}

                    content_list[doc_id].append(tmp)

            result['content_list'] = content_list
            result['project'] = project_data.project

        elif field == 'delete':
            project_data = NoviceRecharge.query.filter_by(project=pid).first()
            db.session.delete(project_data)
            db.session.commit()
            project_data = NoviceRecharge.query.filter_by(project=pid).first()
            if (project_data is None):
                result = {'msg': '删除成功', 'ret': 0}
            else:
                result = {'msg': '删除失败', 'ret': 1}

        elif field == 'clone':
            result = {'msg': '添加成功', 'ret': 0}
            new_project_data = NoviceRecharge(
                basic=project_data.basic, goal_list=project_data.goal_list)
            db.session.add(new_project_data)
            db.session.commit()

            project_id = new_project_data.project
            if (project_id is None):
                result = {'msg': '添加失败', 'ret': 2}

        elif field == 'goal_list':
            reward = rewardList()
            reward = reward['name']
            bonus_list = json.loads(project_data.goal_list)
            result_bonus = {}
            for idx in range(len(bonus_list)):
                total_value = bonus_list[idx]['total_value']
                event_ui = bonus_list[idx]['event_ui']
                score = bonus_list[idx]['score']
                reward_data = bonus_list[idx]['reward']

                for i in range(len(reward_data)):
                    item_type = reward_data[i]['a'][0]
                    item_id = reward_data[i]['a'][1]
                    item_num = reward_data[i]['a'][2]
                    item_rate = 1
                    item_price = 100
                    item_pos = idx
                    if item_type in reward and str(item_id) in reward[item_type]:
                        item_name = reward[item_type][str(item_id)]
                    else:
                        item_name = 'ERROR'

                    if item_pos not in result_bonus:
                        result_bonus[item_pos] = {}
                        result_bonus[item_pos]['total_value'] = total_value
                        result_bonus[item_pos]['event_ui'] = event_ui
                        result_bonus[item_pos]['score'] = score
                        result_bonus[item_pos]['reward'] = []

                    tmp = {"type": item_type, "id": item_id, "num": item_num, "rate": item_rate, "price": item_price,
                           "pos": item_pos, "name": item_name, "total_value": total_value, "event_ui": event_ui, "score": score}

                    result_bonus[item_pos]['reward'].append(tmp)
            result = {'project': project_data.project, 'bonus': result_bonus}
    return jsonify(result)


@app.route('/evip_shop_item_index', methods=['GET'])
def evip_shop_item_index():
    data = EvipShopItem.query.all()
    result = []
    for d in data:
        project = int(d.project)
        if d.remark:
            remark = json.loads(d.remark)
            title = remark['title']
        else:
            title = 'title'

        tmp = {"project": project, "title": title}
        result.append(tmp)

    return jsonify(result)


@app.route('/evip_shop_item_delete/<int:item_id>', methods=['GET'])
def evip_shop_item_delete(item_id):
    pid = session['pid']
    project_data = EvipShopItem.query.filter_by(project=pid).first()

    goods_list = json.loads(project_data.goods)

    new_goods_list = []
    for x in range(len(goods_list)):
        if x == item_id:
            continue
        new_goods_list.append(goods_list[x])

    sql_data = json.dumps(new_goods_list)
    EvipShopItem.query.filter_by(project=pid).update({'goods': sql_data})

    db.session.commit()
    return jsonify({'msg': '更新成功', 'ret': 0})


@app.route('/down_evip_shop_item/<int:is_push>', methods=['GET', 'POST'])
def down_evip_shop_item(is_push):
    result_data = {}
    project_data = EvipShopItem.query.all()
    for p in project_data:
        project_id = str(p.project)
        goods = json.loads(p.goods)

        result_data[project_id] = {}
        result_data[project_id]['goods'] = {}
        result_data[project_id]['goods'] = goods

    response = DownLoad('evip_item_tool_shop_proj', result_data, is_push)

    return response


@app.route('/evip_item_shop_action', methods=['GET', 'POST'])
def evip_item_shop_action():
    post_data = json.loads(request.data)

    goods_list = []
    for x in range(len(post_data)):
        update_data = post_data[x]

        item_type = int(update_data['item_type'])
        item_id = int(update_data['item_id'])

        item_num = int(update_data['item_num'])
        good_type = int(update_data['good_type'])
        good_id = int(update_data['good_id'])
        price = int(update_data['price'])
        raw_price = int(update_data['raw_price'])
        limit_lv = int(update_data['limit_lv'])
        limit_time = int(update_data['limit_time'])
        weight = int(update_data['weight'])
        epoch_id = int(update_data['epoch_id'])

        tmp = {}
        tmp['a'] = [item_type, item_id, item_num]
        tmp['sale_price'] = [good_type, good_id, price, raw_price]
        tmp['limit_lv'] = limit_lv
        tmp['limit_time'] = limit_time
        tmp['weight'] = weight
        tmp['epoch_id'] = epoch_id
        tmp['id'] = str(item_type)+'_'+str(item_id) + \
            '_'+str(item_num)+'_'+str(x)

        goods_list.append(tmp)

    pid = session['pid']

    EvipShopItem.query.filter_by(project=pid).update(
        {'goods': json.dumps(goods_list)})
    db.session.commit()

    return jsonify({'msg': '更新成功', 'ret': 0})


@app.route('/evip_shop_item_basic/<field>/<int:pid>', methods=['GET'])
def evip_shop_item_basic(field, pid=0):
    if pid != 0:
        session['pid'] = pid
    pid = session['pid']
    project_data = EvipShopItem.query.filter_by(project=pid).first()
    if (project_data is None):
        result = {'msg': '找不到数据'}
    else:
        if field == 'basic':
            reward = rewardList()
            reward = reward['name']

            result = {}
            data = json.loads(project_data.goods)
            goods_list = []
            for x in range(len(data)):
                tmp = data[x]
                tmp['item_type'] = tmp['a'][0]
                tmp['item_id'] = tmp['a'][1]
                tmp['item_num'] = tmp['a'][2]
                tmp['item_name'] = reward[tmp['item_type']
                                          ][str(tmp['item_id'])]

                tmp['good_type'] = tmp['sale_price'][0]
                tmp['good_id'] = tmp['sale_price'][1]
                tmp['good_name'] = reward[tmp['good_type']
                                          ][str(tmp['good_id'])]
                tmp['raw_price'] = tmp['sale_price'][3]
                tmp['price'] = tmp['sale_price'][2]
                tmp['idx'] = x
                del tmp['a']
                del tmp['sale_price']
                goods_list.append(tmp)

            if project_data.remark is None:
                result['title'] = ''
            else:
                remark = json.loads(project_data.remark)
                result['title'] = remark['title']

            result['goods_list'] = goods_list
            result['project'] = project_data.project

        elif field == 'delete':
            project_data = EvipShopItem.query.filter_by(project=pid).first()
            db.session.delete(project_data)
            db.session.commit()
            project_data = EvipShopItem.query.filter_by(project=pid).first()
            if (project_data is None):
                result = {'msg': '删除成功', 'ret': 0}
            else:
                result = {'msg': '删除失败', 'ret': 1}

        elif field == 'clone':
            result = {'msg': '添加成功', 'ret': 0}
            new_project_data = EvipShopItem(goods=project_data.goods,remark=project_data.remark)
            db.session.add(new_project_data)
            db.session.commit()

            project_id = new_project_data.project
            if (project_id is None):
                result = {'msg': '添加失败', 'ret': 2}
    return jsonify(result)


@app.route('/evip_item_shop_title', methods=['GET', 'POST'])
def evip_item_shop_title():

    post_data = json.loads(request.data)

    project = post_data['project']
    title = post_data['title']

    data = {"title": title}

    EvipShopItem.query.filter_by(project=project).update(
        {'remark': json.dumps(data)})

    return jsonify({'ret': 0})


@app.route('/multiday_recharge_index', methods=['GET'])
def multiday_recharge_index():
    data = MultidayRecharge.query.all()
    result = []
    for d in data:
        project = int(d.project)
        info = json.loads(d.basic)
        title = info['localization']['1']['title']

        remark = ''
        if 'remark' in info:
            remark = info['remark']
        tmp = {"project": project, "title": title, 'remark': remark}

        result.append(tmp)

    return jsonify(result)


@app.route('/multiday_recharge_basic/<field>/<int:pid>', methods=['GET'])
def multiday_recharge_basic(field, pid=0):
    if pid != 0:
        session['pid'] = pid
    pid = session['pid']
    project_data = MultidayRecharge.query.filter_by(project=pid).first()
    if (project_data is None):
        result = {'msg': '找不到数据'}
    else:
        if field == 'basic':

            result = json.loads(project_data.basic)
            result['project'] = project_data.project

        elif field == 'delete':
            project_data = MultidayRecharge.query.filter_by(
                project=pid).first()
            db.session.delete(project_data)
            db.session.commit()
            project_data = MultidayRecharge.query.filter_by(
                project=pid).first()
            if (project_data is None):
                result = {'msg': '删除成功', 'ret': 0}
            else:
                result = {'msg': '删除失败', 'ret': 1}

        elif field == 'clone':
            result = {'msg': '添加成功', 'ret': 0}
            new_project_data = MultidayRecharge(
                basic=project_data.basic, target=project_data.target)
            db.session.add(new_project_data)
            db.session.commit()

            project_id = new_project_data.project
            if (project_id is None):
                result = {'msg': '添加失败', 'ret': 2}

        elif field == 'target':
            reward = rewardList()
            reward = reward['name']
            bonus_list = json.loads(project_data.target)
            result_bonus = {}
            for idx in range(len(bonus_list)):
                score = bonus_list[idx]['score']
                reward_data = bonus_list[idx]['reward']

                for i in range(len(reward_data)):
                    item_type = reward_data[i]['a'][0]
                    item_id = reward_data[i]['a'][1]
                    item_num = reward_data[i]['a'][2]
                    item_rate = 1
                    item_price = 100
                    item_pos = idx
                    if item_type in reward and str(item_id) in reward[item_type]:
                        item_name = reward[item_type][str(item_id)]
                    else:
                        item_name = 'ERROR'

                    if item_pos not in result_bonus:
                        result_bonus[item_pos] = {}
                        result_bonus[item_pos]['score'] = score
                        result_bonus[item_pos]['reward'] = []

                    tmp = {"type": item_type, "id": item_id, "num": item_num, "rate": item_rate,
                           "price": item_price, "pos": item_pos, "name": item_name, "score": score}

                    result_bonus[item_pos]['reward'].append(tmp)
            result = {'project': project_data.project, 'bonus': result_bonus}
    return jsonify(result)


@app.route('/multiday_recharge_action', methods=['POST'])
def multiday_recharge_action():
    params = json.loads(request.data)
    _type = params['type']
    if _type == 'get_doc_id_list':
        resp = get_doc_id_list_in_operation_event_english('multiday_charge_event', 'title')
        return jsonify({
            'status': resp['status'],
            'doc_id_list': resp['doc_id_list']
        })
    return jsonify({})


@app.route('/update_multiday_recharge', methods=['GET', 'POST'])
def update_multiday_recharge():

    update_data = json.loads(request.data)
    project_id = session['pid']

    update_type = update_data['update_type']
    project_id = update_data['project']

    if 'project' in update_data:
        update_data.pop('project')

    update_data.pop('update_type')

    sql_data = json.dumps(update_data)

    if update_type == 'basic':
        sql_data = json.dumps(update_data)
        MultidayRecharge.query.filter_by(
            project=project_id).update({'basic': sql_data})

    elif update_type == 'target':
        rank_reward_data = []
        bonus_list = update_data['bonus']
        for idx in bonus_list:
            data = bonus_list[idx]
            score = int(data['score'])
            reward = []
            for r_idx in range(len(data['reward'])):
                item_type = int(data['reward'][r_idx]['type'])
                item_id = int(data['reward'][r_idx]['id'])
                item_num = int(data['reward'][r_idx]['num'])
                tmp = {}
                tmp['a'] = [item_type, item_id, item_num]
                reward.append(tmp)

            rank_reward_data.append({"score": score, "reward": reward})

        MultidayRecharge.query.filter_by(project=project_id).update(
            {'target': json.dumps(rank_reward_data)})
    elif update_type == 'remark':
        project_data = MultidayRecharge.query.filter_by(
            project=project_id).first()
        basic_data = json.loads(project_data.basic)
        basic_data['remark'] = update_data['remark']
        MultidayRecharge.query.filter_by(project=project_id).update(
            {'basic': json.dumps(basic_data)})

    db.session.commit()
    return jsonify({'msg': '更新成功', 'ret': 0})


@app.route('/down_multiday_recharge/<int:is_push>', methods=['GET', 'POST'])
def down_multiday_recharge(is_push):
    result_data = {}
    project_data = MultidayRecharge.query.all()
    with open(GLOBAL_PATH + 'new_operation_event.json', encoding='utf-8') as f:
        new_operation_event_data = json.load(f)
    for p in project_data:
        project_id = str(p.project)
        basic = json.loads(p.basic)
        target = json.loads(p.target)

        if 'remark' in basic:
            del basic['remark']

        result_data[project_id] = {}
        result_data[project_id]['basic'] = {}
        result_data[project_id]['basic']['event_ui'] = int(basic['event_ui'])

        multiday_recharge_localization = {}
        for i in range(0, 21):
            current_localization = ''
            if 'multiday_charge_event' in new_operation_event_data:
                if str(basic['doc_id']) in new_operation_event_data['multiday_charge_event']:
                    if str(i) in new_operation_event_data['multiday_charge_event'][str(basic['doc_id'])]:
                        current_localization = \
                            new_operation_event_data['multiday_charge_event'][str(basic['doc_id'])][str(i)][
                                'title']
            multiday_recharge_localization[str(i + 1)] = {
                'title': current_localization
            }

        # result_data[project_id]['localization'] = {}
        # result_data[project_id]['localization'] = basic['localization']
        result_data[project_id]['localization'] = multiday_recharge_localization
        result_data[project_id]['localization_doc'] = {
            'title': basic['doc_id']
        }

        result_data[project_id]['target'] = {}
        result_data[project_id]['target'] = target

    response = DownLoad('multiday_recharge_proj', result_data, is_push)

    return response


@app.route('/castle_lv_index', methods=['GET'])
def castle_lv_index():
    data = CastleLv.query.all()
    result = []
    for d in data:
        project = int(d.project)
        info = json.loads(d.basic)
        title = info['localization']['1']['title']
        tmp = {"project": project, "title": title}
        result.append(tmp)

    return jsonify(result)


@app.route('/castle_lv_basic/<field>/<int:pid>', methods=['GET'])
def castle_lv_basic(field, pid=0):

    if pid != 0:
        session['pid'] = pid

    pid = session['pid']

    project_data = CastleLv.query.filter_by(project=pid).first()
    if (project_data is None):
        result = {'msg': '找不到数据'}
    else:
        if field == 'basic':
            basic = json.loads(project_data.basic)
            if '_tag' not in basic:
                basic['_tag'] = []
            result = basic
            result['project'] = project_data.project

        elif field == 'castle_lv':
            reward = rewardList()
            reward = reward['name']
            bonus_list = json.loads(project_data.castle_lv)
            result_bonus = {}
            for idx in range(len(bonus_list)):
                lv = bonus_list[idx]['lv']
                reward_data = bonus_list[idx]['reward']

                for i in range(len(reward_data)):
                    item_type = reward_data[i]['a'][0]
                    item_id = reward_data[i]['a'][1]
                    item_num = reward_data[i]['a'][2]
                    item_rate = 1
                    item_price = 100
                    item_pos = idx
                    if item_type in reward and str(item_id) in reward[item_type]:
                        item_name = reward[item_type][str(item_id)]
                    else:
                        item_name = 'ERROR'

                    if item_pos not in result_bonus:
                        result_bonus[item_pos] = {}
                        result_bonus[item_pos]['lv'] = lv
                        result_bonus[item_pos]['reward'] = []

                    tmp = {"type": item_type, "id": item_id, "num": item_num, "rate": item_rate,
                           "price": item_price, "pos": item_pos, "name": item_name, "lv": lv}

                    result_bonus[item_pos]['reward'].append(tmp)
            result = {'project': project_data.project, 'bonus': result_bonus}
        elif field == 'delete':
            print(pid)
            project_data = CastleLv.query.filter_by(project=pid).first()
            db.session.delete(project_data)
            db.session.commit()
            project_data = CastleLv.query.filter_by(project=pid).first()
            if (project_data is None):
                result = {'msg': '删除成功', 'ret': 0}
            else:
                result = {'msg': '删除失败', 'ret': 1}

    return jsonify(result)


@app.route('/update_castle_lv', methods=['GET', 'POST'])
def update_castle_lv():
    update_data = json.loads(request.data)
    project_id = session['pid']

    update_type = update_data['update_type']
    project_id = update_data['project']

    if 'project' in update_data:
        update_data.pop('project')

    update_data.pop('update_type')

    sql_data = json.dumps(update_data)

    if update_type == 'basic':
        sql_data = json.dumps(update_data)
        CastleLv.query.filter_by(
            project=project_id).update({'basic': sql_data})
    elif update_type == 'castle_lv':
        rank_reward_data = []
        bonus_list = update_data['bonus']
        for idx in bonus_list:
            data = bonus_list[idx]
            lv = int(data['lv'])
            reward = []
            for r_idx in range(len(data['reward'])):
                item_type = int(data['reward'][r_idx]['type'])
                item_id = int(data['reward'][r_idx]['id'])
                item_num = int(data['reward'][r_idx]['num'])
                tmp = {}
                tmp['a'] = [item_type, item_id, item_num]
                reward.append(tmp)

            rank_reward_data.append({"lv": lv, "reward": reward})

        CastleLv.query.filter_by(project=project_id).update(
            {'castle_lv': json.dumps(rank_reward_data)})

    db.session.commit()
    return jsonify({'msg': '更新成功', 'ret': 0})


@app.route('/down_novice_recharge/<int:is_push>', methods=['GET', 'POST'])
def down_novice_recharge(is_push):
    result_data = {}
    project_data = NoviceRecharge.query.all()
    for p in project_data:
        project_id = str(p.project)
        basic = json.loads(p.basic)
        goal_list = json.loads(p.goal_list)

        result_data[project_id] = {}

        result_data[project_id]['localization'] = {}
        result_data[project_id]['localization'] = basic['localization']

        result_data[project_id]['goal_list'] = {}
        result_data[project_id]['goal_list'] = goal_list

    response = DownLoad('novice_recharge_proj', result_data, is_push)

    return response


@app.route('/down_castle_lv/<int:is_push>', methods=['GET', 'POST'])
def down_castle_lv(is_push):
    result_data = {}
    project_data = CastleLv.query.all()
    for p in project_data:
        project_id = str(p.project)
        basic = json.loads(p.basic)
        castle_lv = json.loads(p.castle_lv)
        _tag = basic['_tag'] if '_tag' in basic else []

        result_data[project_id] = {}
        result_data[project_id]['basic'] = {}
        result_data[project_id]['basic']['event_ui'] = int(basic['event_ui'])
        result_data[project_id]['activity_time'] = int(basic['activity_time'])
        result_data[project_id]['show_time'] = int(basic['show_time'])

        result_data[project_id]['localization'] = {}
        result_data[project_id]['localization'] = basic['localization']

        result_data[project_id]['castle_lv'] = {}
        result_data[project_id]['castle_lv'] = castle_lv
        result_data[project_id]['_tag'] = _tag

    response = DownLoad('castle_lv_proj', result_data, is_push)

    return response


@app.route('/clone_castle_lv/<int:pid>', methods=['GET'])
def clone_castle_lv(pid):
    result = {'msg': '添加成功', 'ret': 0}
    project_data = CastleLv.query.filter_by(project=pid).first()
    if (project_data is None):
        result = {'msg': '找不到数据', 'ret': 1}
    else:
        new_project_data = CastleLv(
            basic=project_data.basic, castle_lv=project_data.castle_lv)
        db.session.add(new_project_data)
        db.session.commit()

        project_id = new_project_data.project

        if (project_id is None):
            result = {'msg': '添加失败', 'ret': 2}

    return jsonify(result)


@app.route('/lucky_card_index', methods=['GET'])
def lucky_card_index():
    data = LuckyCard.query.all()
    result = []
    for d in data:
        project = int(d.project)
        info = json.loads(d.basic)
        title = info['lang']['1']['title']
        tmp = {"project": project, "title": title}
        result.append(tmp)

    return jsonify(result)


@app.route('/lucky_card_basic/<field>/<int:pid>', methods=['GET'])
def lucky_card_basic(field, pid=0):

    if field == 'basic' and pid != 0:
        session['pid'] = pid

    pid = session['pid']

    project_data = LuckyCard.query.filter_by(project=pid).first()
    if (project_data is None):
        result = {'msg': '找不到数据'}
    else:
        if field == 'basic':
            reward = rewardList()
            reward = reward['name']
            result = json.loads(project_data.basic)
            ticket_type = result['ticket'][0]
            ticket_name = reward[ticket_type][str(result['ticket'][1])]
            result['ticket'] = [ticket_type, result['ticket'][1], ticket_name]
            result['project'] = project_data.project

        elif field == 'big_reward':
            reward = rewardList()
            reward = reward['name']
            result_bonus = {}
            big_reward = json.loads(project_data.big_reward)
            for x in range(len(big_reward)):
                item_type = big_reward[x]['a'][0]
                item_id = big_reward[x]['a'][1]
                item_num = big_reward[x]['a'][2]
                item_price = 100
                item_pos = 0
                item_show_lv = 0
                item_weight = 0
                if item_type in reward and str(item_id) in reward[item_type]:
                    item_name = reward[item_type][str(item_id)]
                else:
                    item_name = 'ERROR'

                tmp = {"type": item_type, "id": item_id, "num": item_num, "weight": item_weight,
                       "show_lv": item_show_lv, "price": item_price, "pos": item_pos, "name": item_name, }
                if item_pos not in result_bonus:
                    result_bonus[item_pos] = {}
                    result_bonus[item_pos]['reward'] = []

                result_bonus[item_pos]['reward'].append(tmp)
            result = {'project': project_data.project, 'bonus': result_bonus}

        elif field == 'card_reward':
            reward = rewardList()
            reward = reward['name']
            result_bonus = {}
            card_reward = json.loads(project_data.card_reward)
            for x in range(len(card_reward)):
                item_type = card_reward[x]['a'][0]
                item_id = card_reward[x]['a'][1]
                item_num = card_reward[x]['a'][2]
                item_price = 100
                item_pos = 1
                item_show_lv = card_reward[x]['s']
                item_weight = card_reward[x]['w']
                if item_type in reward and str(item_id) in reward[item_type]:
                    item_name = reward[item_type][str(item_id)]
                else:
                    item_name = 'ERROR'

                tmp = {"type": item_type, "id": item_id, "num": item_num, "weight": item_weight,
                       "show_lv": item_show_lv, "price": item_price, "pos": item_pos, "name": item_name, }
                if item_pos not in result_bonus:
                    result_bonus[item_pos] = {}
                    result_bonus[item_pos]['reward'] = []

                result_bonus[item_pos]['reward'].append(tmp)
            result = {'project': project_data.project, 'bonus': result_bonus}

    return jsonify(result)


@app.route('/clone_lucky_card/<int:pid>', methods=['GET'])
def clone_lucky_card(pid):
    result = {'msg': '添加成功', 'ret': 0}
    project_data = LuckyCard.query.filter_by(project=pid).first()
    if (project_data is None):
        result = {'msg': '找不到数据', 'ret': 1}
    else:
        new_project_data = LuckyCard(
            basic=project_data.basic, big_reward=project_data.big_reward, card_reward=project_data.card_reward)
        db.session.add(new_project_data)
        db.session.commit()

        project_id = new_project_data.project

        if (project_id is None):
            result = {'msg': '添加失败', 'ret': 2}

    return jsonify(result)


@app.route('/update_lucky_card', methods=['GET', 'POST'])
def update_lucky_card():

    update_data = json.loads(request.data)
    project_id = session['pid']

    update_type = update_data['update_type']
    project_id = update_data['project']

    if 'project' in update_data:
        update_data.pop('project')

    update_data.pop('update_type')

    sql_data = json.dumps(update_data)

    if update_type == 'basic':
        cost = []
        for x in range(len(update_data['cost'])):
            cost.append(int(update_data['cost'][x]))
        update_data['cost'] = cost
        sql_data = json.dumps(update_data)
        LuckyCard.query.filter_by(
            project=project_id).update({'basic': sql_data})
    elif update_type == 'big_reward':
        sql_data = []
        for x in range(len(update_data['bonus']['0']['reward'])):
            data = update_data['bonus']['0']['reward'][x]
            item_type = int(data['type'])
            item_id = int(data['id'])
            item_num = int(data['num'])
            tmp = {}
            tmp['a'] = [item_type, item_id, item_num]

            sql_data.append(tmp)
        LuckyCard.query.filter_by(project=project_id).update(
            {'big_reward': json.dumps(sql_data)})

    elif update_type == 'card_reward':
        sql_data = []
        for x in range(len(update_data['bonus']['1']['reward'])):
            data = update_data['bonus']['1']['reward'][x]
            item_type = int(data['type'])
            item_id = int(data['id'])
            item_num = int(data['num'])
            show_lv = int(data['show_lv'])
            weight = int(data['weight'])
            tmp = {}
            tmp['a'] = [item_type, item_id, item_num]
            tmp['s'] = show_lv
            tmp['w'] = weight

            sql_data.append(tmp)

        LuckyCard.query.filter_by(project=project_id).update(
            {'card_reward': json.dumps(sql_data)})
    db.session.commit()
    return jsonify({'msg': '更新成功', 'ret': 0})


@app.route('/down_lucky_card/<int:is_push>', methods=['GET', 'POST'])
def down_lucky_card(is_push):
    result_data = {}
    project_data = LuckyCard.query.all()
    for p in project_data:
        project_id = str(p.project)
        basic = json.loads(p.basic)
        big_reward = json.loads(p.big_reward)
        card_reward = json.loads(p.card_reward)

        result_data[project_id] = {}
        result_data[project_id]['basic'] = {}
        result_data[project_id]['basic']['event_ui'] = int(basic['event_ui'])
        result_data[project_id]['basic']['title'] = {}

        result_data[project_id]['info'] = {}
        result_data[project_id]['info']['info'] = {}

        result_data[project_id]['limit'] = {}
        result_data[project_id]['limit']['castle_lv'] = int(basic['castle_lv'])

        info = basic['lang']
        for x in info:
            result_data[project_id]['basic']['title'][x] = info[x]['title']
            result_data[project_id]['info']['info'][x] = info[x]['info']

        result_data[project_id]['info']['ticket'] = basic['ticket']
        result_data[project_id]['info']['cost'] = basic['cost']

        result_data[project_id]['info']['big_reward'] = big_reward
        result_data[project_id]['info']['card_reward'] = card_reward

    response = DownLoad('lucky_card_proj', result_data, is_push)

    return response


@app.route('/lucky_wheel_index', methods=['GET'])
def lucky_wheel_index():
    data = LuckyWheel.query.all()
    result = []
    for d in data:
        project = int(d.project)
        info = json.loads(d.basic)
        title = info['lang']['1']['title']
        if 'remark' not in info:
            remark = 'remark'
        else:
            remark = info['remark']
        tmp = {"project": project, "title": title, 'remark': remark}
        result.append(tmp)

    return jsonify(result)


@app.route('/lucky_wheel_basic/<field>/<int:pid>', methods=['GET'])
def lucky_wheel_basic(field, pid=0):
    if pid != 0:
        session['pid'] = pid
    pid = session['pid']
    project_data = LuckyWheel.query.filter_by(project=pid).first()
    if (project_data is None):
        result = {'msg': '找不到数据'}
    else:
        if field == 'basic':
            result = {'data': {}, 'doc_id_list': []}
            result['data'] = json.loads(project_data.basic)
            result['data']['project'] = project_data.project

            doc_content = GetDocByFilename('wheel_event')
            doc_id_list = []
            for k, v in doc_content.items():
                doc_id_list.append({
                    'value': int(k),
                    'label': '{0}-{1}'.format(k, v['title'])
                    })

            result['doc_id_list'] = doc_id_list

        elif field == 'clone':
            result = {'msg': '添加成功', 'ret': 0}
            new_project_data = LuckyWheel(basic=project_data.basic, big_reward=project_data.big_reward,
                                          wheel_reward=project_data.wheel_reward, goal_reward=project_data.goal_reward)
            db.session.add(new_project_data)
            db.session.commit()

            project_id = new_project_data.project

            if (project_id is None):
                result = {'msg': '添加失败', 'ret': 2}
        elif field == 'delete':
            project_data = LuckyWheel.query.filter_by(project=pid).first()
            db.session.delete(project_data)
            db.session.commit()

            project_data = LuckyWheel.query.filter_by(project=pid).first()
            if (project_data is None):
                result = {'msg': '删除成功', 'ret': 0}
            else:
                result = {'msg': '删除失败', 'ret': 1}

        elif field == 'big_reward':
            reward = rewardList()
            reward = reward['name']
            result_bonus = {}
            big_reward = json.loads(project_data.big_reward)
            for x in range(len(big_reward)):
                item_type = big_reward[x]['a'][0]
                item_id = big_reward[x]['a'][1]
                item_num = big_reward[x]['a'][2]
                item_price = 100
                item_pos = 0
                item_show_lv = 0
                item_weight = 0
                if item_type in reward and str(item_id) in reward[item_type]:
                    item_name = reward[item_type][str(item_id)]
                else:
                    item_name = 'ERROR'
                tmp = {"type": item_type, "id": item_id, "num": item_num, "weight": item_weight,
                       "show_lv": item_show_lv, "price": item_price, "pos": item_pos, "name": item_name}
                if item_pos not in result_bonus:
                    result_bonus[item_pos] = {}
                    result_bonus[item_pos]['reward'] = []

                result_bonus[item_pos]['reward'].append(tmp)
            result = {'project': project_data.project, 'bonus': result_bonus}

        elif field == 'wheel_reward':
            reward = rewardList()
            reward = reward['name']
            result_bonus = {}
            wheel_reward = json.loads(project_data.wheel_reward)
            for x in range(len(wheel_reward)):
                item_type = wheel_reward[x]['a'][0]
                item_id = wheel_reward[x]['a'][1]
                item_num = wheel_reward[x]['a'][2]
                item_price = 100
                item_pos = 1
                item_show_lv = wheel_reward[x]['s']
                item_weight = wheel_reward[x]['w']
                if item_type in reward and str(item_id) in reward[item_type]:
                    item_name = reward[item_type][str(item_id)]
                else:
                    item_name = 'ERROR'

                tmp = {"type": item_type, "id": item_id, "num": item_num, "weight": item_weight,
                       "show_lv": item_show_lv, "price": item_price, "pos": item_pos, "name": item_name}
                if item_pos not in result_bonus:
                    result_bonus[item_pos] = {}
                    result_bonus[item_pos]['reward'] = []

                result_bonus[item_pos]['reward'].append(tmp)
            result = {'project': project_data.project, 'bonus': result_bonus}
        elif field == 'goal_reward':
            reward = rewardList()
            reward = reward['name']

            bonus_list = json.loads(project_data.goal_reward)
            result_bonus = {}
            for idx in range(len(bonus_list)):
                _from = bonus_list[idx]['from']
                _to = bonus_list[idx]['to']
                reward_data = bonus_list[idx]['reward']

                for i in range(len(reward_data)):
                    item_type = reward_data[i]['a'][0]
                    item_id = reward_data[i]['a'][1]
                    item_num = reward_data[i]['a'][2]
                    item_rate = 1
                    item_price = 100
                    item_pos = idx
                    if item_type in reward and str(item_id) in reward[item_type]:
                        item_name = reward[item_type][str(item_id)]
                    else:
                        item_name = 'ERROR'

                    if item_pos not in result_bonus:
                        result_bonus[item_pos] = {}
                        result_bonus[item_pos]['from'] = _from
                        result_bonus[item_pos]['to'] = _to
                        result_bonus[item_pos]['reward'] = []

                    tmp = {"type": item_type, "id": item_id, "num": item_num, "rate": item_rate,
                           "price": item_price, "pos": item_pos, "name": item_name, "from": _from, "to": _to}

                    result_bonus[item_pos]['reward'].append(tmp)
            result = {'project': project_data.project, 'bonus': result_bonus}

    return jsonify(result)


@app.route('/update_lucky_wheel', methods=['GET', 'POST'])
def update_lucky_wheel():

    update_data = json.loads(request.data)
    project_id = session['pid']

    update_type = update_data['update_type']
    project_id = update_data['project']

    if 'project' in update_data:
        update_data.pop('project')

    update_data.pop('update_type')

    sql_data = json.dumps(update_data)

    if update_type == 'basic':
        sql_data = json.dumps(update_data)
        LuckyWheel.query.filter_by(
            project=project_id).update({'basic': sql_data})
    elif update_type == 'big_reward':
        sql_data = []
        for x in range(len(update_data['bonus']['0']['reward'])):
            data = update_data['bonus']['0']['reward'][x]
            item_type = int(data['type'])
            item_id = int(data['id'])
            item_num = int(data['num'])
            tmp = {}
            tmp['a'] = [item_type, item_id, item_num]
            sql_data.append(tmp)
        LuckyWheel.query.filter_by(project=project_id).update(
            {'big_reward': json.dumps(sql_data)})

    elif update_type == 'wheel_reward':
        sql_data = []
        for x in range(len(update_data['bonus']['1']['reward'])):
            data = update_data['bonus']['1']['reward'][x]
            item_type = int(data['type'])
            item_id = int(data['id'])
            item_num = int(data['num'])
            show_lv = int(data['show_lv'])
            weight = int(data['weight'])
            tmp = {}
            tmp['a'] = [item_type, item_id, item_num]
            tmp['s'] = show_lv
            tmp['w'] = weight

            sql_data.append(tmp)

        LuckyWheel.query.filter_by(project=project_id).update(
            {'wheel_reward': json.dumps(sql_data)})
    elif update_type == 'goal_reward':
        rank_reward_data = []

        bonus_list = update_data['bonus']

        for idx in bonus_list:
            data = bonus_list[idx]
            _from = 1
            _to = int(data['to'])
            reward = []
            for r_idx in range(len(data['reward'])):
                item_type = int(data['reward'][r_idx]['type'])
                item_id = int(data['reward'][r_idx]['id'])
                item_num = int(data['reward'][r_idx]['num'])
                tmp = {}
                tmp['a'] = [item_type, item_id, item_num]
                reward.append(tmp)

            rank_reward_data.append(
                {"from": _from, "to": _to, "reward": reward})

        LuckyWheel.query.filter_by(project=project_id).update(
            {'goal_reward': json.dumps(rank_reward_data)})
    db.session.commit()
    return jsonify({'msg': '更新成功', 'ret': 0})


@app.route('/down_lucky_wheel/<int:is_push>', methods=['GET', 'POST'])
def down_lucky_wheel(is_push):
    result_data = {}
    project_data = LuckyWheel.query.all()
    for p in project_data:
        project_id = str(p.project)
        basic = json.loads(p.basic)
        big_reward = json.loads(p.big_reward)
        wheel_reward = json.loads(p.wheel_reward)
        goal_reward = json.loads(p.goal_reward)

        result_data[project_id] = {}

        if 'calendar_doc_id' in basic:
            _calendar_doc_id = basic['calendar_doc_id']
        else:
            _calendar_doc_id = 1
        result_data[project_id]['calendar_conf'] = {
            'event_type': 50,
            'event_ui': 1,
            'order': 1,
            'jump': 1,
            'localization': {
                'title': _calendar_doc_id,
                'info': _calendar_doc_id
            },
            'reward': big_reward,
            'show_type': 0
        }

        result_data[project_id]['basic'] = {}
        result_data[project_id]['basic']['event_ui'] = int(basic['event_ui'])

        result_data[project_id]['basic']['title'] = {}

        result_data[project_id]['info'] = {}
        result_data[project_id]['info']['info'] = {}

        result_data[project_id]['limit'] = {}
        result_data[project_id]['limit']['free_cycle'] = int(
            basic['free_cycle'])
        result_data[project_id]['limit']['discount_cycle'] = int(
            basic['discount_cycle'])
        result_data[project_id]['limit']['chance_cycle'] = int(
            basic['chance_cycle'])
        result_data[project_id]['limit']['chance'] = int(basic['chance'])

        result_data[project_id]['limit']['castle_lv'] = int(basic['castle_lv'])
        result_data[project_id]['limit']['free'] = int(basic['free'])

        result_data[project_id]['limit']['cal_score'] = basic['cal_score']

        result_data[project_id]['limit']['bottom_line'] = basic['bottom_line']
        info = basic['lang']
        for x in info:
            result_data[project_id]['basic']['title'][x] = info[x]['title']
            result_data[project_id]['info']['info'][x] = info[x]['info']

        result_data[project_id]['info']['rotation'] = {}
        result_data[project_id]['info']['rotation']['ticket'] = basic['ticket']

        for d in range(len(basic['discount'])):
            basic['discount'][d][2] = basic['discount'][d][2] * 100

        result_data[project_id]['info']['rotation']['discount'] = basic['discount']

        result_data[project_id]['info']['big_reward'] = big_reward
        result_data[project_id]['info']['wheel_reward'] = wheel_reward
        result_data[project_id]['info']['goal_reward'] = goal_reward

    response = DownLoad('lucky_wheel_proj', result_data, is_push)

    return response


@app.route('/lucky_wheel_remark', methods=['GET', 'POST'])
def lucky_wheel_remark():

    post_data = json.loads(request.data)

    project = post_data['project']
    remark = post_data['remark']

    project_data = LuckyWheel.query.filter_by(project=project).first()

    basic_data = json.loads(project_data.basic)

    basic_data['remark'] = remark

    LuckyWheel.query.filter_by(project=project).update(
        {'basic': json.dumps(basic_data)})

    return jsonify({'ret': 0})


@app.route('/territory_event', methods=['GET'])
def territory_event():
    data = TerritoryEvent.query.all()
    result = []
    for d in data:
        project = int(d.project)
        localization = json.loads(d.localization)
        basic = json.loads(d.basic)
        title = localization['1']['title']
        if 'remark' not in basic:
            remark = ''
        else:
            remark = basic['remark']
        tmp = {"project": project, "title": title, 'remark': remark}
        result.append(tmp)
    return jsonify(result)


@app.route('/territory_event_action', methods=['POST'])
def territory_event_action():
    update_data = json.loads(request.data)

    result = {'msg': '成功', 'ret': 0}

    type = update_data['type']
    project = update_data['project']

    project_data = TerritoryEvent.query.filter_by(project=project).first()

    if type == 'clone':
        new_project_data = TerritoryEvent(
            basic=project_data.basic, localization=project_data.localization)

        db.session.add(new_project_data)
        db.session.commit()

        new_project_id = new_project_data.project
        if (new_project_id is None):
            result = {'msg': '克隆失败', 'ret': 2}
        else:
            result = {'msg': '克隆成功', 'ret': 0}

    elif type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = TerritoryEvent.query.filter_by(
            project=project).first()
        if (new_project_data is None):
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}
    elif type == 'basic':

        result = {}
        result['basic_data'] = json.loads(project_data.basic)
        result['localization_data'] = json.loads(project_data.localization)

    elif type == 'remark':

        remark = update_data['remark']
        basic_data = json.loads(project_data.basic)
        basic_data['remark'] = remark
        TerritoryEvent.query.filter_by(project=project).update(
            {'basic': json.dumps(basic_data)})
        db.session.commit()

    elif type == 'update_basic':

        basic_data = json.dumps(update_data['data'])
        TerritoryEvent.query.filter_by(
            project=project).update({'basic': basic_data})

    return jsonify(result)


@app.route('/territory_event_down/<int:is_push>', methods=['GET', 'POST'])
def territory_event_down(is_push):

    result_data = {}
    project_data = TerritoryEvent.query.all()
    for p in project_data:
        project_id = str(p.project)

        basic_data = json.loads(p.basic)
        if 'remark' in basic_data:
            del basic_data['remark']

        result_data[project_id] = {}
        result_data[project_id]['basic'] = basic_data
        result_data[project_id]['localization'] = json.loads(p.localization)

    response = DownLoad('territory_event_proj', result_data, is_push)

    return response


@app.route('/lohar_event', methods=['GET'])
def lohar_event():
    data = LoharEvent.query.all()
    result = []
    for d in data:
        project = int(d.project)
        localization = json.loads(d.localization)
        basic = json.loads(d.basic)
        title = localization['1']['title']
        if 'remark' not in basic:
            remark = ''
        else:
            remark = basic['remark']
        tmp = {"project": project, "title": title, 'remark': remark}
        result.append(tmp)
    return jsonify(result)


@app.route('/lohar_event_action', methods=['POST'])
def lohar_event_action():
    update_data = json.loads(request.data)

    result = {'msg': '成功', 'ret': 0}

    type = update_data['type']
    project = update_data['project']

    project_data = LoharEvent.query.filter_by(project=project).first()

    if type == 'clone':
        new_project_data = LoharEvent(basic=project_data.basic, localization=project_data.localization,
                                      top_reward=project_data.top_reward, kill_reward=project_data.kill_reward, rate_list=project_data.rate_list)

        db.session.add(new_project_data)
        db.session.commit()

        new_project_id = new_project_data.project
        if (new_project_id is None):
            result = {'msg': '克隆失败', 'ret': 2}
        else:
            result = {'msg': '克隆成功', 'ret': 0}

    elif type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = LoharEvent.query.filter_by(project=project).first()
        if (new_project_data is None):
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}
    elif type == 'basic':
        result = {}
        basic= json.loads(project_data.basic)

        doc_content = GetDocByFilename('luoha_event')
        doc_id_list = []
        for k, v in doc_content.items():
            doc_id_list.append({
                'value': int(k),
                'label': '{0}-{1}'.format(k, v['title'])
                })

        if '_tag' not in basic:
            basic['_tag'] = []

        result['basic_data'] = basic
        result['localization_data'] = json.loads(project_data.localization)
        result['doc_id_list'] = doc_id_list

    elif type == 'remark':

        remark = update_data['remark']
        basic_data = json.loads(project_data.basic)
        basic_data['remark'] = remark
        LoharEvent.query.filter_by(project=project).update(
            {'basic': json.dumps(basic_data)})
        db.session.commit()

    elif type == 'reward_list':

        top_reward = json.loads(project_data.top_reward)
        kill_reward = json.loads(project_data.kill_reward)

        result = {'top_reward': RewardToDic(
            top_reward), 'kill_reward': RewardToDic(kill_reward)}

    elif type == 'rate_list':

        rate_list = json.loads(project_data.rate_list)
        result['rate_list'] = rate_list

    elif type == 'update_basic':
        basic_data = update_data['data']
        if basic_data['has_info_ui'] == 0:
            basic_data['info_ui'] = {}

        basic_data = json.dumps(basic_data)
        LoharEvent.query.filter_by(
            project=project).update({'basic': basic_data})

    elif type == 'update_reward_list':

        top_reward = RewardToTMysql(update_data['top_reward'])
        kill_reward = RewardToTMysql(update_data['kill_reward'])
        LoharEvent.query.filter_by(project=project).update(
            {'top_reward': json.dumps(top_reward), 'kill_reward': json.dumps(kill_reward)})

    elif type == 'update_rate_list':

        rate_list = update_data['taskItem']

        LoharEvent.query.filter_by(project=project).update(
            {'rate_list': json.dumps(rate_list)})

    return jsonify(result)


@app.route('/lohar_event_down/<int:is_push>', methods=['GET', 'POST'])
def lohar_event_down(is_push):

    result_data = {}
    project_data = LoharEvent.query.all()
    for p in project_data:
        project_id = str(p.project)

        basic_data = json.loads(p.basic)

        if 'remark' in basic_data:
            del basic_data['remark']
        if 'has_info_ui' in basic_data:
            del basic_data['has_info_ui']

        if 'icon' in basic_data['info_ui']:
            icon = basic_data['info_ui']['icon']
            if icon != '':
                basic_data['info_ui']['icon'] = list(map(int, icon.split(",")))

        if 'calendar_doc_id' in basic_data:
            _calendar_doc_id = basic_data['calendar_doc_id']
        else:
            _calendar_doc_id = 1
        if 'calendar_doc_id' in basic_data:
            del basic_data['calendar_doc_id']

        # 20221201 活动日历的event_ui和basic内的event_ui保持一致
        calendar_conf = {
            'event_type': 65,
            'event_ui': basic_data['event_ui'],
            'order': 1,
            'jump': 1,
            'localization': {
                'title': _calendar_doc_id,
                'info': _calendar_doc_id
            },
            'reward': json.loads(p.top_reward),
            'show_type': 0
        }

        if '_tag' in basic_data:
            _tag = basic_data['_tag']
            del basic_data['_tag']
        else:
            _tag = []

        result_data[project_id] = {}
        result_data[project_id]['_tag'] = _tag
        result_data[project_id]['calendar_conf'] = calendar_conf
        result_data[project_id]['basic'] = basic_data
        result_data[project_id]['localization'] = json.loads(p.localization)
        result_data[project_id]['top_reward'] = json.loads(p.top_reward)
        result_data[project_id]['kill_reward'] = json.loads(p.kill_reward)
        result_data[project_id]['rate_list'] = json.loads(p.rate_list)

    response = DownLoad('lohar_event_project', result_data, is_push)

    return response


@app.route('/special_map_dis', methods=['GET'])
def special_map_dis():
    data = SpecialMapDis.query.all()
    result = []
    for d in data:
        project = int(d.project)
        conf = json.loads(d.conf)
        wild_id_list = []
        for x in conf:
            wild_id_list.append(x)

        tmp = {"project": project, "wild_id": ','.join(wild_id_list)}
        result.append(tmp)

    return jsonify(result)


@app.route('/special_map_dis_action', methods=['POST'])
def special_map_dis_action():
    update_data = json.loads(request.data)

    result = {'msg': '成功', 'ret': 0}

    type = update_data['type']
    project = update_data['project']

    project_data = SpecialMapDis.query.filter_by(project=project).first()

    if type == 'clone':
        new_project_data = SpecialMapDis(conf=project_data.conf)

        db.session.add(new_project_data)
        db.session.commit()

        new_project_id = new_project_data.project
        if (new_project_id is None):
            result = {'msg': '克隆失败', 'ret': 2}
        else:
            result = {'msg': '克隆成功', 'ret': 0}

    elif type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = SpecialMapDis.query.filter_by(
            project=project).first()
        if (new_project_data is None):
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}

    return jsonify(result)


@app.route('/special_map_dis_down/<int:is_push>', methods=['GET', 'POST'])
def special_map_dis_down(is_push):

    result_data = {}
    project_data = SpecialMapDis.query.all()
    for p in project_data:
        project_id = str(p.project)

        result_data[project_id] = {}
        result_data[project_id]['conf'] = json.loads(p.conf)

    response = DownLoad('special_map_dis_project', result_data, is_push)

    return response


@app.route('/new_alliance_event_score', methods=['POST'])
def new_alliance_event_score():
    update_data = json.loads(request.data)
    result = {'msg': '成功', 'ret': 0}
    type = update_data['type']
    if type == 'init':
        result = {}
        mysql_data = NewAllianceEventScore.query.order_by(
            NewAllianceEventScore.doc_id).all()
        task_list = []
        for p in mysql_data:
            id = int(p.id)
            type = int(p.type)
            id_list = list(map(int, p.id_list.split(",")))
            num = int(p.num)
            score = int(p.score)
            doc_id = int(p.doc_id)
            score_type = p.score_type
            tmp = {'id': id, 'id_list': id_list, 'num': num, 'score': score,
                   'doc_id': doc_id, 'task_type': type, 'score_type': score_type}
            task_list.append(tmp)
        result = score_type_list()
        result['task_list'] = task_list
        return jsonify(result)
    elif type == 'delete':
        id = update_data['id']
        project_data = NewAllianceEventScore.query.filter_by(id=id).first()
        db.session.delete(project_data)
        db.session.commit()
        project_data = NewAllianceEventScore.query.filter_by(id=id).first()
        if (project_data is None):
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}
        return jsonify(result)
    elif type == 'update':
        id = update_data['id']
        task_type = int(update_data['task_type'])
        id_list = update_data['id_list']
        num = int(update_data['num'])
        score = int(update_data['score'])
        doc_id = int(update_data['doc_id'])
        score_type = update_data['score_type']
        if id == -1:
            mysql_data = NewAllianceEventScore(
                id_list=id_list, score=score, num=num, doc_id=doc_id, type=task_type, score_type=score_type)
            db.session.add(mysql_data)
            db.session.commit()
            id = mysql_data.id
        else:
            NewAllianceEventScore.query.filter_by(id=update_data['id']).update(
                {'type': task_type, 'id_list': id_list, 'score': score, 'num': num, 'doc_id': doc_id, 'score_type': score_type})
            db.session.commit()
            id = update_data['id']
        return jsonify({'msg': '更新成功', 'ret': 0, 'id': id})


@app.route('/new_alliance_event', methods=['GET'])
def new_alliance_event():
    data = NewAllianceEvent.query.all()
    result = []
    for d in data:
        project = int(d.project)
        localization = json.loads(d.localization)
        basic = json.loads(d.basic)
        title = localization['1']['title']
        if 'remark' not in basic:
            remark = ''
        else:
            remark = basic['remark']
        tmp = {"project": project, "title": title, 'remark': remark}
        result.append(tmp)
    return jsonify(result)


@app.route('/new_alliance_event_action', methods=['POST'])
def new_alliance_event_action():
    update_data = json.loads(request.data)

    result = {'msg': '成功', 'ret': 0}

    type = update_data['type']
    project = update_data['project']

    project_data = NewAllianceEvent.query.filter_by(project=project).first()

    if type == 'clone':
        new_project_data = NewAllianceEvent(basic=project_data.basic, localization=project_data.localization,
                                            calc_score=project_data.calc_score, reward=project_data.reward,
                                            extern0=project_data.extern0)

        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if (new_project_id is None):
            result = {'msg': '克隆失败', 'ret': 2}
        else:
            result = {'msg': '克隆成功', 'ret': 0}

    elif type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = NewAllianceEvent.query.filter_by(
            project=project).first()
        if (new_project_data is None):
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}
    elif type == 'basic':
        result = {}

        doc_data = loadDocument()
        score_type_list = []
        mysql_data = NewAllianceEventScore.query.order_by(
            NewAllianceEventScore.doc_id).all()
        task_list = []
        for p in mysql_data:
            id = int(p.id)
            num = str(p.num)
            doc_id = str(p.doc_id)
            doc_name = doc_data['doc_scoring_rule'][doc_id]['content'] + \
                "-" + str(doc_id)
            if 'STRING0' in doc_name:
                doc_name = doc_name.replace('STRING0', num)
            tmp = {"label": doc_name, 'value': id}
            score_type_list.append(tmp)

        result['score_type_list'] = score_type_list

        result['basic_data'] = json.loads(project_data.basic)
        result['extern0'] = json.loads(project_data.extern0)
        result['localization_data'] = json.loads(project_data.localization)
    elif type == 'remark':
        remark = update_data['remark']
        basic_data = json.loads(project_data.basic)
        basic_data['remark'] = remark
        NewAllianceEvent.query.filter_by(project=project).update(
            {'basic': json.dumps(basic_data)})
        db.session.commit()

    elif type == 'update_basic':
        data = update_data['data']
        basic_data = json.dumps(data['basic_data'])
        extern0 = json.dumps(data['extern0'])
        NewAllianceEvent.query.filter_by(project=project).update(
            {'basic': basic_data, 'extern0': extern0})

    elif type == 'user_goal':
        reward = rewardList()
        reward = reward['name']

        bonus_list = json.loads(project_data.reward)
        bonus_list = bonus_list['goal_reward']['user']
        result = RankGoalReward(bonus_list)

    elif type == 'alliance_goal':

        bonus_list = json.loads(project_data.reward)
        bonus_list = bonus_list['goal_reward']['alliance']
        result = RankGoalReward(bonus_list)

    elif type == 'alliance_rank':
        bonus_list = json.loads(project_data.reward)
        bonus_list = bonus_list['rank_reward']['alliance']
        result = RankGoalReward(bonus_list)

    elif type == 'update_user_goal':
        bonus_list = update_data['bonus']
        reward = json.loads(project_data.reward)
        reward['goal_reward']['user'] = UpdateRankGoalReward(bonus_list, 0)
        NewAllianceEvent.query.filter_by(project=project).update(
            {'reward': json.dumps(reward)})

    elif type == 'update_alliance_goal':
        bonus_list = update_data['bonus']
        reward = json.loads(project_data.reward)
        reward['goal_reward']['alliance'] = UpdateRankGoalReward(bonus_list, 0)
        NewAllianceEvent.query.filter_by(project=project).update(
            {'reward': json.dumps(reward)})

    elif type == 'update_alliance_rank':
        bonus_list = update_data['bonus']
        reward = json.loads(project_data.reward)
        reward['rank_reward']['alliance'] = UpdateRankGoalReward(bonus_list, 1)
        NewAllianceEvent.query.filter_by(project=project).update(
            {'reward': json.dumps(reward)})

    return jsonify(result)


@app.route('/new_alliance_event_down/<int:is_push>', methods=['GET', 'POST'])
def new_alliance_event_down(is_push):

    mysql_data = NewAllianceEventScore.query.all()
    task_list = {}
    for p in mysql_data:
        id = int(p.id)
        type = int(p.type)
        id_list = list(map(int, p.id_list.split(",")))
        num = int(p.num)
        score = int(p.score)
        doc_id = int(p.doc_id)
        score_type = list(map(int, p.score_type.split(",")))

        task_list[str(id)] = {"type": type, "id_list": id_list, "num": num,
                              "score": score, "doc_id": doc_id, 'score_type': score_type}

    result_data = {}
    project_data = NewAllianceEvent.query.all()
    for p in project_data:

        project_id = str(p.project)
        result_data[project_id] = {}
        basic = json.loads(p.basic)
        result_data[project_id]['basic'] = {}
        result_data[project_id]['basic']['event_ui'] = basic['event_ui']
        result_data[project_id]['reward'] = json.loads(p.reward)
        result_data[project_id]['extern0'] = json.loads(p.extern0)
        result_data[project_id]['extern1'] = {}
        result_data[project_id]['localization'] = json.loads(p.localization)

        calc_score_list = []
        for i in range(len(basic['score_id_list'])):
            score_id = str(basic['score_id_list'][i])
            calc_score_list.append(task_list[score_id])

        calc_score_list.append(
            {"type": 79, "num": 1, "score": 0, "score_type": [], "id_list": [-1], "doc_id": 0})

        result_data[project_id]['calc_score'] = {}
        result_data[project_id]['calc_score']['score_type_list'] = calc_score_list
    result_data['event_main_type'] = 67

    response = DownLoad('new_alliance_event_project', result_data, is_push)

    return response


@app.route('/new_personal_event_score', methods=['POST'])
def new_personal_event_score():
    update_data = json.loads(request.data)
    result = {'msg': '成功', 'ret': 0}
    type = update_data['type']
    if type == 'init':
        result = {}
        mysql_data = NewPersonalEventScore.query.order_by(
            NewPersonalEventScore.doc_id).all()
        task_list = []
        for p in mysql_data:
            id = int(p.id)
            type = int(p.type)
            id_list = list(map(int, p.id_list.split(",")))
            num = int(p.num)
            score = int(p.score)
            doc_id = int(p.doc_id)
            target_unit = int(p.target_unit)
            show_type = int(p.show_type)
            tmp = {'id': id, 'id_list': id_list, 'num': num,
                   'score': score, 'doc_id': doc_id, 'task_type': type, 'target_unit': target_unit,'show_type': show_type}
            task_list.append(tmp)
        result = score_type_list()
        result['task_list'] = task_list
        result['show_list'] = [{"label":"无","value":0},{"label":"满研究","value":1}]
        return jsonify(result)
    elif type == 'delete':
        id = update_data['id']
        project_data = NewPersonalEventScore.query.filter_by(id=id).first()
        db.session.delete(project_data)
        db.session.commit()
        project_data = NewPersonalEventScore.query.filter_by(id=id).first()
        if (project_data is None):
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}
        return jsonify(result)
    elif type == 'update':
        id = update_data['id']
        task_type = int(update_data['task_type'])
        id_list = update_data['id_list']
        num = int(update_data['num'])
        score = int(update_data['score'])
        doc_id = int(update_data['doc_id'])
        target_unit = int(update_data['target_unit'])
        show_type = int(update_data['show_type'])
        if id == -1:
            mysql_data = NewPersonalEventScore(
                id_list=id_list, score=score, num=num, doc_id=doc_id, type=task_type, target_unit=target_unit, show_type=show_type)
            db.session.add(mysql_data)
            db.session.commit()
            id = mysql_data.id
        else:
            NewPersonalEventScore.query.filter_by(id=update_data['id']).update(
                {'type': task_type, 'id_list': id_list, 'score': score, 'num': num, 'doc_id': doc_id, 'target_unit': target_unit, 'show_type': show_type})
            db.session.commit()
            id = update_data['id']
        return jsonify({'msg': '更新成功', 'ret': 0, 'id': id})


@app.route('/new_personal_event', methods=['GET'])
def new_personal_event():
    data = NewPersonalEvent.query.all()
    result = []
    for d in data:
        project = int(d.project)
        localization = json.loads(d.localization)
        basic = json.loads(d.basic)
        title = localization['1']['title']
        if 'remark' not in basic:
            remark = ''
        else:
            remark = basic['remark']
        tmp = {"project": project, "title": title, 'remark': remark}
        result.append(tmp)
    return jsonify(result)


@app.route('/new_personal_event_action', methods=['POST'])
def new_personal_event_action():
    update_data = json.loads(request.data)

    result = {'msg': '成功', 'ret': 0}

    type = update_data['type']
    project = update_data['project']

    project_data = NewPersonalEvent.query.filter_by(project=project).first()

    if type == 'clone':
        new_project_data = NewPersonalEvent(basic=project_data.basic, localization=project_data.localization,
                                            calc_score=project_data.calc_score, reward=project_data.reward,
                                            extern0=project_data.extern0)

        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if (new_project_id is None):
            result = {'msg': '克隆失败', 'ret': 2}
        else:
            result = {'msg': '克隆成功', 'ret': 0}

    elif type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = NewPersonalEvent.query.filter_by(
            project=project).first()
        if (new_project_data is None):
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}
    elif type == 'basic':
        result = {}

        doc_data = loadDocument()
        score_type_list = []
        mysql_data = NewPersonalEventScore.query.order_by(
            NewPersonalEventScore.doc_id).all()
        task_list = []
        for p in mysql_data:
            id = int(p.id)
            num = str(p.num)
            doc_id = str(p.doc_id)
            if doc_id not in doc_data['doc_scoring_rule']:
                doc_name = 'ERROR'
            else:
                doc_name = doc_data['doc_scoring_rule'][doc_id]['content'] + \
                "-" + str(doc_id)
            if 'STRING0' in doc_name:
                doc_name = doc_name.replace('STRING0', num)
            tmp = {"label": doc_name, 'value': id}
            score_type_list.append(tmp)

        result['score_type_list'] = score_type_list

        result['basic_data'] = json.loads(project_data.basic)
        result['extern0'] = json.loads(project_data.extern0)
        result['localization_data'] = json.loads(project_data.localization)
    elif type == 'remark':
        remark = update_data['remark']
        basic_data = json.loads(project_data.basic)
        basic_data['remark'] = remark
        NewPersonalEvent.query.filter_by(project=project).update(
            {'basic': json.dumps(basic_data)})
        db.session.commit()

    elif type == 'update_basic':
        data = update_data['data']
        basic_data = json.dumps(data['basic_data'])
        extern0 = json.dumps(data['extern0'])
        NewPersonalEvent.query.filter_by(project=project).update(
            {'basic': basic_data, 'extern0': extern0})

    elif type == 'user_goal':
        reward = rewardList()
        reward = reward['name']

        bonus_list = json.loads(project_data.reward)
        bonus_list = bonus_list['goal_reward']['user']
        result = RankGoalReward(bonus_list)
    elif type == 'user_rank':
        bonus_list = json.loads(project_data.reward)
        bonus_list = bonus_list['rank_reward']['user']
        result = RankGoalReward(bonus_list)

    elif type == 'update_user_goal':
        bonus_list = update_data['bonus']
        reward = json.loads(project_data.reward)
        reward['goal_reward']['user'] = UpdateRankGoalReward(bonus_list, 0)
        NewPersonalEvent.query.filter_by(project=project).update(
            {'reward': json.dumps(reward)})

    elif type == 'update_user_rank':
        bonus_list = update_data['bonus']
        reward = json.loads(project_data.reward)
        reward['rank_reward']['user'] = UpdateRankGoalReward(bonus_list, 1)
        NewPersonalEvent.query.filter_by(project=project).update(
            {'reward': json.dumps(reward)})

    return jsonify(result)


@app.route('/new_personal_event_down/<int:is_push>', methods=['GET', 'POST'])
def new_personal_event_down(is_push):

    mysql_data = NewPersonalEventScore.query.all()
    task_list = {}
    for p in mysql_data:
        id = int(p.id)
        type = int(p.type)
        id_list = list(map(int, p.id_list.split(",")))
        num = int(p.num)
        score = int(p.score)
        doc_id = int(p.doc_id)
        target_unit = int(p.target_unit)
        if int(p.show_type) == 0:
            show_type = []
        else:
            show_type = [{"type":int(p.show_type),"value":0}]
        num = target_unit * num

        task_list[str(id)] = {"type": type, "id_list": id_list,
                              "num": num, "score": score, "doc_id": doc_id, "target_unit": target_unit, "show": show_type}
    result_data = {}
    project_data = NewPersonalEvent.query.all()
    for p in project_data:

        project_id = str(p.project)
        result_data[project_id] = {}
        basic = json.loads(p.basic)
        result_data[project_id]['basic'] = {}
        result_data[project_id]['basic']['event_ui'] = basic['event_ui']
        result_data[project_id]['reward'] = json.loads(p.reward)
        result_data[project_id]['extern0'] = json.loads(p.extern0)
        result_data[project_id]['extern1'] = {}
        result_data[project_id]['localization'] = json.loads(p.localization)

        calc_score_list = []
        for i in range(len(basic['score_id_list'])):
            score_id = str(basic['score_id_list'][i])
            calc_score_list.append(task_list[score_id])

        result_data[project_id]['calc_score'] = {}
        result_data[project_id]['calc_score']['score_type_list'] = calc_score_list
    result_data['event_main_type'] = 66

    response = DownLoad('new_personal_event_project', result_data, is_push)

    return response


@app.route('/notice_event', methods=['GET'])
def notice_event():
    data = NoticeEvent.query.all()
    result = []
    for d in data:
        project = int(d.project)
        localization = json.loads(d.localization)
        basic = json.loads(d.basic)
        if 'localization' in localization:
            title = localization['localization']['1']['title']
        else:
            title = '文案有误'

        if 'remark' not in basic:
            remark = ''
        else:
            remark = basic['remark']
        tmp = {"project": project, "title": title, 'remark': remark}
        result.append(tmp)
    return jsonify(result)


@app.route('/notice_event_action', methods=['POST'])
def notice_event_action():
    update_data = json.loads(request.data)

    result = {'msg': '成功', 'ret': 0}

    type = update_data['type']
    project = update_data['project']

    project_data = NoticeEvent.query.filter_by(project=project).first()

    if type == 'clone':
        new_project_data = NoticeEvent(basic=project_data.basic, localization=project_data.localization,
                                       top_reward=project_data.top_reward, navigation=project_data.navigation)

        db.session.add(new_project_data)
        db.session.commit()

        new_project_id = new_project_data.project
        if (new_project_id is None):
            result = {'msg': '克隆失败', 'ret': 2}
        else:
            result = {'msg': '克隆成功', 'ret': 0}

    elif type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = NoticeEvent.query.filter_by(project=project).first()
        if (new_project_data is None):
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}

    elif type == 'basic':
        result = {}
        basic = json.loads(project_data.basic)

        result['basic_data'] = basic
        result['top_reward'] = RewardShowToDoc(json.loads(project_data.top_reward))

        common_buff_project = read_s3_file('common_buff_project')
        common_buff_list = []
        for node in common_buff_project:
            common_buff_list.append({
                'label': '{0}-{1}'.format(node['value'], node['label']),
                'value': node['value']
                })

        result['common_buff_list'] = common_buff_list

        doc_content = GetDocByFilename('notice_event')
        doc_id_list = []
        for k, v in doc_content.items():
            doc_id_list.append({
                'value': int(k),
                'label': '{0}-{1}'.format(k, v['title'])
                })

        result['doc_id_list'] = doc_id_list

    elif type == 'remark':
        remark = update_data['remark']
        basic_data = json.loads(project_data.basic)
        basic_data['remark'] = remark
        NoticeEvent.query.filter_by(project=project).update(
            {'basic': json.dumps(basic_data)})
        db.session.commit()

    elif type == 'top_reward':

        top_reward = json.loads(project_data.top_reward)

        result = {'top_reward': RewardToDic(top_reward)}

    elif type == 'navigation':

        navigation = json.loads(project_data.navigation)

        for x in range(len(navigation)):
            top_reward = RewardToDic(navigation[x]['top_reward'])
            navigation[x]['top_reward'] = top_reward[0]

        result['navigation'] = navigation

    elif type == 'update_basic':
        basic_data = update_data['basic_data']
        top_reward = RewardToTMysqlNew(update_data['top_reward'])

        NoticeEvent.query.filter_by(
            project=project).update({'basic': json.dumps(basic_data), 'top_reward': json.dumps(top_reward)})

    elif type == 'update_top_reward':

        top_reward = RewardToTMysql(update_data['top_reward'])

        NoticeEvent.query.filter_by(project=project).update(
            {'top_reward': json.dumps(top_reward)})

    elif type == 'update_navigation':

        taskItemList = update_data['taskItem']

        navigation = []
        for x in range(len(taskItemList)):
            item_data = taskItemList[x]

            tmp_reward = []
            for i in range(len(item_data['top_reward']['reward'])):
                r = item_data['top_reward']['reward'][i]
                reward_tmp = {}
                reward_tmp['a'] = [int(r['type']), int(r['id']), int(r['num'])]
                tmp_reward.append(reward_tmp)

            tmp = {"icon": item_data['icon'], "event_type": item_data['event_type'],
                   'event_id': item_data['event_id'], "top_reward": tmp_reward}
            navigation.append(tmp)

        NoticeEvent.query.filter_by(project=project).update(
            {'navigation': json.dumps(navigation)})

    return jsonify(result)


@app.route('/notice_event_down/<int:is_push>', methods=['GET', 'POST'])
def notice_event_down(is_push):
    result_data = {}
    project_data = NoticeEvent.query.all()
    for p in project_data:
        project_id = str(p.project)

        basic_data = json.loads(p.basic)

        if 'remark' in basic_data:
            del basic_data['remark']
        if 'calendar_doc' in basic_data:
            del basic_data['calendar_doc']

        if 'calendar_doc_id' in basic_data:
            _calendar_doc_id = basic_data['calendar_doc_id']
        else:
            _calendar_doc_id = 1

        # 20221201 活动日历的event_ui和basic内的event_ui保持一致
        calendar_conf = {
            'event_type': 68,
            'event_ui': basic_data['event_ui'],
            'order': 1,
            'jump': 1,
            'localization': {
                'title': _calendar_doc_id,
                'info': _calendar_doc_id
            },
            'reward': json.loads(p.top_reward),
            'show_type': 0
        }

        if 'common_buff_pid' in basic_data:
            common_buff_pid = basic_data['common_buff_pid']
            del basic_data['common_buff_pid']
        else:
            common_buff_pid = -1

        localization_data = json.loads(p.localization)

        info_config = []
        if 'info_config' in localization_data:
            info_config = localization_data['info_config']
        localization = {}
        if 'localization' in localization_data:
            localization = localization_data['localization']

        for node in localization:
            localization[node]['navigation'] = []

        result_data[project_id] = {}
        result_data[project_id]['calendar_conf'] = calendar_conf
        result_data[project_id]['common_buff_pid'] = common_buff_pid
        result_data[project_id]['basic'] = basic_data
        result_data[project_id]['top_reward'] = json.loads(p.top_reward)
        result_data[project_id]['localization'] = localization
        result_data[project_id]['info_config'] = info_config

    response = DownLoad('notice_event_proj', result_data, is_push)

    return response


@app.route('/make_cake_event', methods=['GET'])
def make_cake_event():
    data = MakeCakeEvent.query.all()
    result = []
    for d in data:
        project = int(d.project)
        localization = json.loads(d.localization)
        basic = json.loads(d.basic)
        title = localization['1']['title']
        if 'remark' not in basic:
            remark = ''
        else:
            remark = basic['remark']
        tmp = {"project": project, "title": title, 'remark': remark}
        result.append(tmp)
    return jsonify(result)


@app.route('/make_cake_event_action', methods=['POST'])
def make_cake_event_action():
    update_data = json.loads(request.data)

    result = {'msg': '成功', 'ret': 0}

    _type = update_data['type']
    project = update_data['project']

    project_data = MakeCakeEvent.query.filter_by(project=project).first()

    if _type == 'clone':
        new_project_data = MakeCakeEvent(
            basic=project_data.basic,
            localization=project_data.localization,
            goal_reward=project_data.goal_reward,
            extern0=project_data.extern0)

        db.session.add(new_project_data)
        db.session.commit()

        new_project_id = new_project_data.project
        if (new_project_id is None):
            result = {'msg': '克隆失败', 'ret': 2}
        else:
            result = {'msg': '克隆成功', 'ret': 0}

    elif _type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = MakeCakeEvent.query.filter_by(
            project=project).first()
        if (new_project_data is None):
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}

    elif _type == 'basic':
        result = {}
        extern0 = json.loads(project_data.extern0)
        basic = json.loads(project_data.basic)
        if '_tag' not in basic:
            basic['_tag'] = []
        result['basic_data'] = basic
        result['unlock'] = extern0['unlock']
        result['localization_data'] = json.loads(project_data.localization)

    elif _type == 'remark':

        remark = update_data['remark']
        basic_data = json.loads(project_data.basic)
        basic_data['remark'] = remark
        MakeCakeEvent.query.filter_by(project=project).update(
            {'basic': json.dumps(basic_data)})
        db.session.commit()

    elif _type == 'goal_reward':
        reward_item_list = rewardList()['name']
        goal_reward = json.loads(project_data.goal_reward)
        for x in range(len(goal_reward)):
            goal_reward[x]['idx'] = x
            reward = goal_reward[x]['reward']
            goal_reward[x]['new_reward'] = []
            for a in range(len(reward)):
                tmp = {"from": a, "to": a, "reward": reward[a]}
                goal_reward[x]['new_reward'].append(tmp)
            goal_reward[x]['new_reward'] = RankGoalReward(goal_reward[x]['new_reward'], reward_item_list)['bonus']
            del goal_reward[x]['reward']

        for node in goal_reward:
            tmp = [node['new_reward'][0]['reward'],
                   node['new_reward'][1]['reward'],
                   node['new_reward'][2]['reward']]
            node['new_reward'] = tmp

        result = {'goal_reward': goal_reward}

    elif _type == 'lv_up':

        extern0_data = json.loads(project_data.extern0)
        lv_up = extern0_data['lv_up']

        for x in range(len(lv_up)):
            new_cost = [lv_up[x]['cost']]
            lv_up[x]['reward'] = RewardToDic(new_cost)[0]
            del lv_up[x]['cost']

        result = {'lv_up': lv_up}

    elif _type == 'extra_reward':

        extern0_data = json.loads(project_data.extern0)
        if 'extra_reward' not in extern0_data:
            extra_reward = {"exp_conf": '', "lv_conf": '', "reward": []}
        else:
            extra_reward = extern0_data['extra_reward']

        extra_reward['reward'] = RankGoalReward(
            extra_reward['reward'])['bonus']

        result = {'extra_reward': extra_reward}

    elif _type == 'update_extra_reward':

        extra_reward = update_data['extra_reward']

        extra_reward['reward'] = UpdateRankGoalReward(
            extra_reward['reward'], 1)

        extern0_data = json.loads(project_data.extern0)

        extern0_data['extra_reward'] = extra_reward

        MakeCakeEvent.query.filter_by(project=project).update(
            {'extern0': json.dumps(extern0_data)})

    elif _type == 'update_lv_up':
        lv_up_data = update_data['lv_up_data']
        new_lv_up_data = []
        for x in range(len(lv_up_data)):
            exp = int(lv_up_data[x]['exp'])

            reward = lv_up_data[x]['reward']['reward']
            cost = {}
            if len(reward) > 0:
                cost = {"a": [reward[0]['type'],
                              reward[0]['id'], reward[0]['num']]}
            tmp = {"exp": exp, "cost": cost, "rate": lv_up_data[x]['rate']}

            new_lv_up_data.append(tmp)

        extern0_data = json.loads(project_data.extern0)
        extern0_data['lv_up'] = new_lv_up_data

        MakeCakeEvent.query.filter_by(project=project).update(
            {'extern0': json.dumps(extern0_data)})

    elif _type == 'update_basic':
        extern0_data = json.loads(project_data.extern0)

        basic_data = update_data['basic_data']
        extern0_data['unlock'] = update_data['unlock']
        basic_data = json.dumps(basic_data)
        extern0_data = json.dumps(extern0_data)
        MakeCakeEvent.query.filter_by(project=project).update(
            {'basic': basic_data, 'extern0': extern0_data})

    elif _type == 'update_goal_reward':
        data = update_data['data']
        goal_reward = []
        for x in range(len(data)):
            show_lv = int(data[x]['show_lv'])
            bigger = int(data[x]['bigger'])
            target = int(data[x]['target'])
            new_reward = data[x]['new_reward']
            reward = []
            for r_list in new_reward:
                tmp_reward = []
                for r in range(len(r_list)):
                    tmp = {
                        "a": [
                            r_list[r]['type'],
                            r_list[r]['id'],
                            r_list[r]['num']
                        ]
                    }
                    tmp_reward.append(tmp)
                reward.append(tmp_reward)

            goal_reward.append({
                "target": target,
                "show_lv": show_lv,
                "bigger": bigger,
                "reward": reward
                })

        MakeCakeEvent.query.filter_by(project=project).update(
            {'goal_reward': json.dumps(goal_reward)})

    return jsonify(result)


@app.route('/make_cake_event_down/<int:is_push>', methods=['GET', 'POST'])
def make_cake_event_down(is_push):
    result_data = {}
    project_data = MakeCakeEvent.query.all()
    for p in project_data:
        project_id = str(p.project)

        basic_data = json.loads(p.basic)

        if 'remark' in basic_data:
            del basic_data['remark']
        extern0 = json.loads(p.extern0)

        new_extern0_reward = []

        for x in range(len(extern0['extra_reward']['reward'])):
            new_extern0_reward.append(
                extern0['extra_reward']['reward'][x]['reward'])

        extern0['extra_reward']['reward'] = new_extern0_reward

        if '_tag' in basic_data:
            _tag = basic_data['_tag']
            del basic_data['_tag']
        else:
            _tag = []

        result_data[project_id] = {}
        result_data[project_id]['_tag'] = _tag
        result_data[project_id]['basic'] = basic_data
        result_data[project_id]['goal_reward'] = json.loads(p.goal_reward)
        result_data[project_id]['localization'] = json.loads(p.localization)
        result_data[project_id]['extern0'] = extern0

    response = DownLoad('make_cake_event_project', result_data, is_push)

    return response


@app.route('/battle_pass', methods=['GET'])
def battle_pass():
    data = BattlePass.query.all()
    result = []
    for d in data:
        project = int(d.project)
        basic = json.loads(d.basic)
        if 'remark' not in basic:
            remark = ''
        else:
            remark = basic['remark']
        tmp = {"project": project, "title": '', 'remark': remark}
        result.append(tmp)
    return jsonify(result)


@app.route('/battle_pass_task_action', methods=['POST'])
def battle_pass_task_action():
    update_data = json.loads(request.data)
    result = {'msg': '成功', 'ret': 0}
    _type = update_data['type']
    if _type == 'task':
        # used_pid
        idx_map_pids = {}
        bp_query = BattlePass.query.all()
        for bp_que in bp_query:
            bp_pid = bp_que.project
            pb_special_task = json.loads(bp_que.special_task)
            bp_normal_task = json.loads(bp_que.normal_task)
            for bp_idx in pb_special_task['task_list']:
                if bp_idx not in idx_map_pids:
                    idx_map_pids[bp_idx] = []
                idx_map_pids[bp_idx].append(bp_pid)

            for bp_idx in bp_normal_task['task_list'][0]:
                if bp_idx not in idx_map_pids:
                    idx_map_pids[bp_idx] = []
                    idx_map_pids[bp_idx].append(bp_pid)
                else:
                    if bp_pid not in idx_map_pids[bp_idx]:
                        idx_map_pids[bp_idx].append(bp_pid)

        result['task'] = []
        project_data = BattlePassTask.query.order_by(BattlePassTask.idx).all()
        for p in project_data:
            data = json.loads(p.data)
            data_idx = p.idx
            if 'extra' not in data:
                data['extra'] = {'epoch_id': -1, "fun_type": []}
            data['pid'] = int(p.project)

            if data_idx in idx_map_pids:
                data['used_pid'] = idx_map_pids[data_idx]
            else:
                data['used_pid'] = []

            result['task'].append(data)

        for idx, node in enumerate(result['task']):
            node['idx'] = idx

        with open(STATIC_PATH + 'battle_pass_task.json', 'r', encoding='utf-8') as f:
            battle_pass_task = json.load(f)

        new_battle_pass_task = []
        for tid in battle_pass_task:
            for node in battle_pass_task[tid]:
                label = node['label']
            new_battle_pass_task.append({"value":int(tid),"label":label})

        result['battle_pass_task'] = new_battle_pass_task

    elif _type == 'update_task':
        with open(STATIC_PATH + 'battle_pass_task.json', 'r', encoding='utf-8') as f:
            battle_pass_task = json.load(f)

        for x in battle_pass_task:
            for node in battle_pass_task[x]:
                detail_flag = 0
                for i in range(len(node['detail'])):
                    if len(node['detail'][i]) > 0:
                        detail_flag = 1
                if detail_flag == 0:
                    node['detail'] = []
                del node['value']
                del node['label']

        task_data = update_data['task']
        for x in range(len(task_data)):
            data = task_data[x]
            if 'idx' in data:
                del data['idx']
            if 'used_pid' in data:
                del data['used_pid']
            id_list = data['id']
            data['rule_list'] = []
            for y in range(len(id_list)):
                _id = str(id_list[y])
                data['rule_list'] = battle_pass_task[_id]

            pid = data['pid']
            del data['pid']
            if pid == -1:
                mysql_data = BattlePassTask(data=json.dumps(data), idx=x)
                db.session.add(mysql_data)
                db.session.commit()
            else:
                BattlePassTask.query.filter_by(project=pid).update(
                    {'data': json.dumps(data), 'idx': x})
                db.session.commit()
    elif _type == 'delete':
        _id = update_data['id']
        project_data = BattlePassTask.query.filter_by(project=_id).first()
        db.session.delete(project_data)
        db.session.commit()
        project_data = BattlePassTask.query.filter_by(project=_id).first()
        if (project_data is None):
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}
        return jsonify(result)
    return jsonify(result)


@app.route('/battle_pass_action', methods=['POST'])
def battle_pass_action():
    """
    20230511 优化
    svn://10.10.0.188/wa_op/运营工具需求/需求池/WG/WG 活动组周需求/具体需求20230421/5.2.1普通季卡工具需求_aurora.rp
    """
    update_data = json.loads(request.data)

    result = {'msg': '成功', 'ret': 0}

    _type = update_data['type']
    project = update_data['project']

    project_data = BattlePass.query.filter_by(project=project).first()

    if _type == 'clone':
        new_project_data = BattlePass(basic=project_data.basic, goal_reward=project_data.goal_reward,
                                      extra_reward=project_data.extra_reward, points_reward=project_data.points_reward,
                                      privilege=project_data.privilege, normal_task=project_data.normal_task,
                                      special_task=project_data.special_task)

        db.session.add(new_project_data)
        db.session.commit()

        new_project_id = new_project_data.project
        if (new_project_id is None):
            result = {'msg': '克隆失败', 'ret': 2}
        else:
            result = {'msg': '克隆成功', 'ret': 0}

    elif _type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = BattlePass.query.filter_by(project=project).first()
        if (new_project_data is None):
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}

    elif _type == 'basic':
        result = {}

        with open(STATIC_PATH + 'battle_pass_task_doc.json', encoding='utf-8') as f:
            task_doc_data = json.load(f)

        basic_data = json.loads(project_data.basic)
        if '_tag' not in basic_data:
            basic_data['_tag'] = []
        result['basic_data'] = basic_data
        result['privilege'] = json.loads(project_data.privilege)

        normal_task = json.loads(project_data.normal_task)
        normal_task['task_list'] = [normal_task['task_list'][0]]
        result['normal_task'] = normal_task

        result['special_task'] = json.loads(project_data.special_task)

        project_data = BattlePassTask.query.order_by(BattlePassTask.idx).all()
        task_list = []
        for p in project_data:
            data = json.loads(p.data)
            project = p.project
            idx = p.idx

            _id = data['id'][0]
            points = data['points']
            target_num = data['target_num']

            if str(_id) in task_doc_data:
                label = task_doc_data[str(_id)]['7']['doc']
                label = label.replace('STRING0', str(target_num))
                label += f'得{points}分'
            else:
                label = '注意: 得分项文案未配置_' + str(project)
            task_list.append({"value": idx, "label": label})
        result['task_list'] = task_list

    elif _type == 'remark':
        remark = update_data['remark']
        basic_data = json.loads(project_data.basic)
        basic_data['remark'] = remark
        BattlePass.query.filter_by(project=project).update(
            {'basic': json.dumps(basic_data)})
        db.session.commit()

    elif _type == 'goal_reward_basic':
        goal_reward = json.loads(project_data.goal_reward)
        reward = rewardList()
        basic_reward = goal_reward['basic']
        elite_reward = goal_reward['elite']
        max_size = max(len(basic_reward), len(elite_reward))
        new_bonus = [{} for _ in range(max_size)]
        for i in range(max_size):
            tmp = {}
            if i < len(basic_reward):
                basic_node = basic_reward[i]
                tmp = {
                    'idx': i,
                    'resbox': basic_node['resbox'],
                    'reward': RewardShowToDoc(basic_node['reward'], reward['name']),
                    'elite_reward': [],
                    'show_lv': basic_node['show_lv'],
                    'special_lv': basic_node['special_lv'],
                    'status': basic_node['status']
                }
            if i < len(elite_reward):
                elite_node = elite_reward[i]
                if not tmp:
                    tmp = {
                        'idx': i,
                        'resbox': elite_node['resbox'],
                        'reward': [],
                        'elite_reward': RewardShowToDoc(elite_node['reward'], reward['name']),
                        'show_lv': elite_node['show_lv'],
                        'special_lv': elite_node['special_lv'],
                        'status': elite_node['status']
                    }
                else:
                    tmp['elite_reward'] = RewardShowToDoc(elite_node['reward'], reward['name'])
            new_bonus[i] = tmp
        result['bonus'] = new_bonus

    elif _type == 'goal_reward_elite':
        goal_reward = json.loads(project_data.goal_reward)
        reward = rewardList()
        result = BattleGoalReward(goal_reward['elite'], reward)

    elif _type == 'extra_reward':
        reward_item_list = rewardList()['name']
        extra_reward = json.loads(project_data.extra_reward)

        extra_reward['basic']['reward'] = RewardShowToDoc(
            extra_reward['basic']['reward'], reward_item_list)
        extra_reward['elite']['reward'] = RewardShowToDoc(
            extra_reward['elite']['reward'], reward_item_list)

        basic_node = {
            'idx': 0,
            'delta_lv': extra_reward['basic']['delta_lv'],
            'reward': extra_reward['basic']['reward']
        }
        elite_node = {
            'idx': 1,
            'delta_lv': extra_reward['elite']['delta_lv'],
            'reward': extra_reward['elite']['reward']
        }
        new_extra_reward = [basic_node, elite_node]

        result['extra_reward'] = new_extra_reward

    elif _type == 'points_reward':
        reward_item_list = rewardList()['name']
        points_reward = json.loads(project_data.points_reward)
        new_points_reward = {
            'basic_reward': RewardShowToDoc(points_reward[0], reward_item_list),
            'elite_reward': RewardShowToDoc(points_reward[1], reward_item_list)
        }
        result['points_reward'] = new_points_reward

    elif _type == 'update_basic':
        basic_data = update_data['basic_data']
        privilege_data = update_data['privilege']
        special_task = update_data['special_task']
        normal_task = update_data['normal_task']
        normal_task['task_list'] = [normal_task['task_list'][0]]

        basic_data = json.dumps(basic_data)
        privilege = json.dumps(privilege_data)

        special_task = json.dumps(special_task)

        normal_task = json.dumps(normal_task)
        BattlePass.query.filter_by(project=project).update(
            {'basic': basic_data, 'privilege': privilege, 'normal_task': normal_task, 'special_task': special_task})

    elif _type == 'update_goal_reward_basic':
        reward = UpdateBattleGoalReward(update_data['bonus'])
        goal_reward = json.loads(project_data.goal_reward)
        goal_reward['basic'] = reward
        BattlePass.query.filter_by(project=project).update(
            {'goal_reward': json.dumps(goal_reward)})

    elif _type == 'update_goal_reward_elite':
        reward = UpdateBattleGoalReward(update_data['bonus'])
        goal_reward = json.loads(project_data.goal_reward)
        goal_reward['elite'] = reward
        BattlePass.query.filter_by(project=project).update(
            {'goal_reward': json.dumps(goal_reward)})

    elif _type == 'update_extra_reward':
        data = update_data['extra_reward']
        basic_node = {
            'delta_lv': data[0]['delta_lv'],
            'reward': RewardToTMysqlNew(data[0]['reward'])
        }
        elite_node = {
            'delta_lv': data[1]['delta_lv'],
            'reward': RewardToTMysqlNew(data[1]['reward'])
        }
        extra_reward = {
            'basic': basic_node, 'elite': elite_node
        }
        BattlePass.query.filter_by(project=project).update(
            {'extra_reward': json.dumps(extra_reward)})

    elif _type == 'update_points_reward':
        data = update_data['points_reward']
        basic_list = RewardToTMysqlNew(data['basic_reward'])
        elite_list = RewardToTMysqlNew(data['elite_reward'])
        points_reward = [basic_list, elite_list]

        BattlePass.query.filter_by(project=project).update(
            {'points_reward': json.dumps(points_reward)})

    elif _type == 'get_doc_id_list':
        resp = get_doc_id_list_in_operation_event_english('norm_card_event', 'title', no_label=False)
        return jsonify({
            'status': resp['status'],
            'doc_id_list': resp['doc_id_list']
        })

    elif _type == 'update_goal_reward':
        data = update_data['bonus']
        basic = []
        elite = []
        for node in data:
            basic_tmp = {
                'show_lv': node['show_lv'],
                'special_lv': node['special_lv'],
                'status': node['status'],
                'reward': RewardToTMysqlNew(node['reward']),
                'resbox': node['resbox']
            }
            basic.append(basic_tmp)

            elite_tmp = {
                'show_lv': node['show_lv'],
                'special_lv': node['special_lv'],
                'status': node['status'],
                'reward': RewardToTMysqlNew(node['elite_reward']),
                'resbox': node['resbox']
            }
            elite.append(elite_tmp)
        goal_reward = {
            'basic': basic,
            'elite': elite
        }
        BattlePass.query.filter_by(project=project).update(
            {'goal_reward': json.dumps(goal_reward)})

    return jsonify(result)


@app.route('/battle_pass_down/<int:is_push>', methods=['GET', 'POST'])
def battle_pass_down(is_push):
    """
    20230511 优化
    svn://10.10.0.188/wa_op/运营工具需求/需求池/WG/WG 活动组周需求/具体需求20230421/5.2.1普通季卡工具需求_aurora.rp
    """
    proj = {}

    with open(STATIC_PATH + 'battle_pass_task_doc.json', encoding='utf-8') as f:
        task_doc_data = json.load(f)
    with open(STATIC_PATH + 'battle_pass_epoch_fun_type.json', encoding='utf-8') as f:
        epoch_fun_type_data = json.load(f)

    project_data = BattlePass.query.all()
    for p in project_data:
        project_id = str(p.project)
        basic_data = json.loads(p.basic)

        if 'remark' in basic_data:
            del basic_data['remark']

        rank = {
            "svr_rank_num": int(basic_data['svr_rank_num']),
            "world_rank_num": int(basic_data['world_rank_num'])
        }

        del basic_data['svr_rank_num']
        del basic_data['world_rank_num']

        privilege = json.loads(p.privilege)
        max_res_list = privilege['max_res_list'].split(",")

        goal_reward = json.loads(p.goal_reward)

        elite_reward = copy.deepcopy(goal_reward['elite'])
        basic_reward = copy.deepcopy(goal_reward['basic'])

        for x in range(len(basic_reward)):
            if 'resbox' in basic_reward[x]:
                del goal_reward['basic'][x]['resbox']
            goal_reward['basic'][x]['special_lv'] = goal_reward['basic'][x]['show_lv']

        for x in range(len(elite_reward)):
            reward = elite_reward[x]['reward']
            for y in range(len(reward)):
                if reward[y]['a'][0] == 110 and 'resbox' in elite_reward[x]:
                    # goal_reward['elite'][x]['reward'][y]['resbox'] = list(
                    #     map(int, elite_reward[x]['resbox'].split(",")))
                    if x == 49:
                        goal_reward['elite'][x]['reward'][y]['resbox'] = [
                            1600000,
                            4000000,
                            4000000,
                            4000000,
                            4000000
                        ]
                    elif x == 94:
                        goal_reward['elite'][x]['reward'][y]['resbox'] = [
                            2800000,
                            7000000,
                            7000000,
                            7000000,
                            7000000
                        ]

            if 'resbox' in goal_reward['elite'][x]:
                del goal_reward['elite'][x]['resbox']

            goal_reward['elite'][x]['special_lv'] = goal_reward['elite'][x]['show_lv']

        if '_tag' in basic_data:
            _tag = basic_data['_tag']
            del basic_data['_tag']
        else:
            _tag = []

        privilege['max_res_list'] = list(map(int, max_res_list))
        proj[project_id] = {}
        proj[project_id]['_tag'] = _tag
        proj[project_id]['basic'] = basic_data
        proj[project_id]['goal_reward'] = goal_reward
        proj[project_id]['extra_reward'] = json.loads(p.extra_reward)
        proj[project_id]['normal_task'] = json.loads(p.normal_task)
        proj[project_id]['special_task'] = json.loads(p.special_task)
        proj[project_id]['points_reward'] = json.loads(p.points_reward)
        proj[project_id]['privilege'] = privilege
        proj[project_id]['rank'] = rank

    task_list = []
    project_data = BattlePassTask.query.order_by(BattlePassTask.idx).all()
    for p in project_data:
        data = json.loads(p.data)
        _id = data['id'][0]
        localization = task_doc_data[str(_id)]
        epoch_id = epoch_fun_type_data[str(_id)]['epoch_id']
        if epoch_fun_type_data[str(_id)]['fun_type'] == -1:
            fun_type = []
        else:
            fun_type = [epoch_fun_type_data[str(_id)]['fun_type']]

        tmp = {
            'localization': localization,
            'points': data['points'],
            'task_type': 0,
            'rule_list': data['rule_list'],
            'target_num': data['target_num']
        }
        if epoch_id != -1:
            tmp['extra'] = {
                'epoch_id': epoch_id,
                'fun_type': fun_type
            }

        # del data['id']
        # if data['extra']['epoch_id'] == -1:
        #     del data['extra']
        task_list.append(tmp)
    result_data = {"proj": proj, 'task': task_list}
    response = DownLoad('battle_pass_event_proj', result_data, is_push)

    return response


@app.route('/lost_battlefield', methods=['GET'])
def lost_battlefield():
    data = LostBattlefield.query.all()
    result = []
    for d in data:
        project = int(d.project)
        remark = str(d.remark)
        basic = json.loads(d.basic)
        new_wild_init = []
        if 'wild_init' in basic:
            wild_init = basic['wild_init']
            for wild_id in wild_init:
                tmp = {"id":int(wild_id),"value":wild_init[wild_id]}
                new_wild_init.append(tmp)
        basic['wild_init'] = new_wild_init
        tmp = {"project": project, 'remark': remark, 'basic': basic}
        result.append(tmp)
    return jsonify(result)


@app.route('/lost_battlefield_action', methods=['POST'])
def lost_battlefield_action():
    update_data = json.loads(request.data)
    result = {'msg': '成功', 'ret': 0}
    type = update_data['type']
    project = update_data['project']
    project_data = LostBattlefield.query.filter_by(project=project).first()
    if type == 'clone':
        new_project_data = LostBattlefield(
            basic=project_data.basic, remark=project_data.remark+"_clone", achievement=project_data.achievement, localization=project_data.localization)
        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if (new_project_id is None):
            result = {'msg': '克隆失败', 'ret': 2}
        else:
            result = {'msg': '克隆成功', 'ret': 0}
    elif type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = LostBattlefield.query.filter_by(
            project=project).first()
        if (new_project_data is None):
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}
    elif type == 'remark':
        remark = update_data['remark']
        LostBattlefield.query.filter_by(
            project=project).update({'remark': remark})
        db.session.commit()
    elif type == 'update':
        data = update_data['data']
        wild_init = data['basic']['wild_init']

        new_wild_init = {}
        for w in range(len(wild_init)):
            id = str(wild_init[w]['id'])
            value = wild_init[w]['value']
            new_wild_init[id] = int(value)
        data['basic']['wild_init'] = new_wild_init
        basic_data = json.dumps(data['basic'])
        LostBattlefield.query.filter_by(
            project=project).update({'basic': basic_data})

    elif type == 'achievement':

        name = update_data['name']
        with open(STATIC_PATH + 'lost_kingdom_building.json', encoding='utf8') as f:
            lost_kingdom_building = json.load(f)

        achievement = json.loads(project_data.achievement)
        task_list = achievement[name]
        for x in range(len(task_list)):
            task_list[x]['id'] = x
            task_list[x]['reward'] = RewardToDic(task_list[x]['reward'])[0]

        result['task_list'] = task_list
        result['lost_kingdom_building'] = lost_kingdom_building

    elif type == 'update_achievement':
        name = update_data['name']
        task_list = update_data['task_list']
        for x in range(len(task_list)):

            if 'id' in task_list[x]:
                del task_list[x]['id']
            if name == 'alliance':
                task_list[x]['task_id'] = 10000 + x
            else:
                task_list[x]['task_id'] = 20000 + x

            reward = task_list[x]['reward']['reward']
            new_reward = []
            for r in range(len(reward)):
                tmp = {}
                tmp['a'] = [int(reward[r]['type']),reward[r]['id'],reward[r]['num']]
                new_reward.append(tmp)

            task_list[x]['reward'] = new_reward

        achievement = json.loads(project_data.achievement)
        achievement[name] = task_list

        LostBattlefield.query.filter_by(project=project).update({'achievement':json.dumps(achievement)})
        db.session.commit()

    return jsonify(result)


@app.route('/lost_battlefield_down/<int:is_push>', methods=['GET', 'POST'])
def lost_battlefield_down(is_push):
    proj = {}
    project_data = LostBattlefield.query.all()
    for p in project_data:
        project_id = str(p.project)
        proj[project_id] = {}
        proj[project_id]['basic'] = json.loads(p.basic)
        # proj[project_id]['localization'] = json.loads(p.localization)
        # proj[project_id]['achievement'] = json.loads(p.achievement)
    response = DownLoad('lost_battlefield_proj', proj, is_push)
    return response

@app.route('/chronicle', methods=['GET'])
def chronicle():
    data = Chronicle.query.all()
    result = []
    for d in data:
        project = int(d.project)
        remark = str(d.remark)
        tmp = {"project": project,'remark': remark}
        result.append(tmp)
    return jsonify(result)


@app.route('/chronicle_action', methods=['POST'])
def chronicle_action():
    update_data = json.loads(request.data)

    result = {'msg': '成功', 'ret': 0}

    type = update_data['type']
    project = update_data['project']

    project_data = Chronicle.query.filter_by(project=project).first()

    if type == 'clone':
        new_project_data = Chronicle(min_castle_lv=project_data.min_castle_lv, localization=project_data.localization,
                                         tasks=project_data.tasks, remark=project_data.remark)

        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if (new_project_id is None):
            result = {'msg': '克隆失败', 'ret': 2}
        else:
            result = {'msg': '克隆成功', 'ret': 0}

    elif type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = Chronicle.query.filter_by(
            project=project).first()
        if (new_project_data is None):
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}
    elif type == 'remark':
        remark = update_data['remark']
        Chronicle.query.filter_by(project=project).update({'remark': remark})
        db.session.commit()

    elif type == 'task':
        tasks = json.loads(project_data.tasks)

        tasks_list = copy.deepcopy(tasks)
        for idx in range(len(tasks_list)):
            rank_reward = tasks_list[idx]['rank_reward']
            special_reward = tasks_list[idx]['special_reward']
            tasks[idx]['rank_reward'] = RankGoalReward(rank_reward)['bonus']
            tasks[idx]['rank_reward_num'] = len(rank_reward)
            tasks[idx]['special_reward_num'] = len(special_reward)
            tasks[idx]['id'] = idx

        chronicle_task = {}
        with open(STATIC_PATH + 'chronicle_task.json', encoding='utf8') as f:
            chronicle_task = json.load(f)

        result = {"tasks":tasks,"task_list":chronicle_task,"castle_lv":project_data.min_castle_lv}

    elif type == 'update_tasks':

        chronicle_task = {}
        with open(STATIC_PATH + 'chronicle_task.json', encoding='utf8') as f:
            data = json.load(f)
            for x in range(len(data)):
                type = str(data[x]['type'])
                chronicle_task[type] = data[x]

        tasks = update_data['tasks']
        castle_lv = int(update_data['castle_lv'])

        new_task = []
        for t in range(len(tasks)):
            type = str(tasks[t]['detail'][0])

            chronicle = chronicle_task[type]

            task_tmp = {}
            task_tmp['task_id'] = t
            task_tmp['has_rank'] = chronicle['has_rank']
            task_tmp['rank_type'] = chronicle['rank']
            if int(type) == 15:
                task_tmp['need_settlement'] = 0
            else:
                task_tmp['need_settlement'] = 1

            task_tmp['task_time'] = tasks[t]['task_time']
            task_tmp['show_rank'] = tasks[t]['show_rank']
            task_tmp['task_class'] = chronicle['task_class']
            task_tmp['reward_size'] = 200
            task_tmp['rank_show_size'] = 100
            task_tmp['castle_lv'] = castle_lv
            task_tmp['event_ui'] = tasks[t]['event_ui']

            rank_reward = tasks[t]['rank_reward']
            task_tmp['rank_reward'] = []
            if rank_reward:
                for x in rank_reward:
                    _from = int(rank_reward[x]['from'])
                    _to = int(rank_reward[x]['to'])
                    reward = rank_reward[x]['reward']
                    if len(reward) == 0:
                        continue
                    tmp_reward = []
                    for r in range(len(reward)):
                        tmp = {"a":[reward[r]['type'],reward[r]['id'],reward[r]['num']]}
                        tmp_reward.append(tmp)
                    tmp = {"from":_from,"to":_to,"reward":tmp_reward}
                    task_tmp['rank_reward'].append(tmp)

            special_reward = tasks[t]['special_reward']
            for x in range(len(special_reward)):
                tmp_type = special_reward[x]['type']
                if tmp_type == 2:
                    special_reward[x]['id'] = -1
                    special_reward[x]['num'] = 0

            task_tmp['special_reward'] = special_reward

            num = chronicle['num']
            if chronicle['level'] == -1:
                level = -1
            else:
                level = int(tasks[t]['detail'][2])

            target = int(tasks[t]['detail'][3])
            op_type = chronicle['op_type']

            task_tmp['detail'] = [int(type),num,level,target,op_type]

            new_task.append(task_tmp)

        # print(json.dumps(new_task))
        Chronicle.query.filter_by(project=project).update({'tasks':json.dumps(new_task),'min_castle_lv':castle_lv})
        db.session.commit()

    return jsonify(result)


@app.route('/chronicle_down/<int:is_push>', methods=['GET', 'POST'])
def chronicle_down(is_push):
    result_data = {}
    project_data = Chronicle.query.all()
    for p in project_data:
        project_id = str(p.project)
        result_data[project_id] = {}
        result_data[project_id]['localization'] = json.loads(p.localization)
        result_data[project_id]['min_castle_lv'] = int(p.min_castle_lv)
        result_data[project_id]['tasks'] = json.loads(p.tasks)

    response = DownLoad('chronicle_proj', result_data, is_push)

    return response

@app.route('/warrior_journey_event_score', methods=['POST'])
def warrior_journey_event_score():
    update_data = json.loads(request.data)
    result = {'msg': '成功', 'ret': 0}
    type = update_data['type']
    if type == 'init':
        name = int(update_data['name'])
        result = {}
        mysql_data = WarriorJourneyEventScore.query.order_by(
            WarriorJourneyEventScore.doc_id).all()
        task_list = []
        for p in mysql_data:
            id = int(p.id)
            score_type = list(map(int,p.score_type.split(",")))
            if name not in score_type:
                continue
            type = int(p.type)
            id_list = json.loads(p.id_list)
            num = int(p.num)
            score = int(p.score)
            doc_id = int(p.doc_id)
            tmp = {'id': id, 'id_list': id_list, 'num': num,
                   'score': score, 'doc_id': doc_id, 'task_type': type, 'score_type': score_type}
            task_list.append(tmp)
        result = score_type_list()
        doc_id_list = copy.deepcopy(result['doc_id_list'])
        task_type_list = copy.deepcopy(result['task_type_list'])
        new_doc_id_list = []
        new_task_type_list = []
        for x in range(len(doc_id_list)):
            id = doc_id_list[x]['value']
            if id >= 293:
                new_doc_id_list.append(doc_id_list[x])
        for x in range(len(task_type_list)):
            id = task_type_list[x]['value']
            if id >= 81 and id <=90:
                new_task_type_list.append(task_type_list[x])
        result['doc_id_list'] = new_doc_id_list
        result['task_type_list'] = new_task_type_list
        result['task_list'] = task_list
        return jsonify(result)
    elif type == 'delete':
        id = update_data['id']
        project_data = WarriorJourneyEventScore.query.filter_by(id=id).first()
        db.session.delete(project_data)
        db.session.commit()
        project_data = WarriorJourneyEventScore.query.filter_by(id=id).first()
        if (project_data is None):
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}
        return jsonify(result)
    elif type == 'update':
        task_list = update_data['task_list']
        for x in range(len(task_list)):
            task = task_list[x]
            id = int(task['id'])
            score_type = ','.join(list(map(str,task['score_type'])))
            task_type = int(task['task_type'])
            id_list = json.dumps(task['id_list'])
            num = int(task['num'])
            score = int(task['score'])
            doc_id = int(task['doc_id'])
            if id == -1:
                mysql_data = WarriorJourneyEventScore(
                    id_list=id_list, score=score, num=num, doc_id=doc_id, type=task_type, score_type=score_type)
                db.session.add(mysql_data)
                db.session.commit()
            else:
                WarriorJourneyEventScore.query.filter_by(id=id).update(
                    {'type': task_type, 'id_list': id_list, 'score': score, 'num': num, 'doc_id': doc_id, 'score_type': score_type})
                db.session.commit()

        return jsonify({'msg': '更新成功', 'ret': 0})


@app.route('/warrior_journey_event', methods=['GET'])
def warrior_journey_event():
    data = WarriorProj.query.all()
    result = []
    for d in data:
        project = int(d.project)
        basic = json.loads(d.basic)
        if 'remark' not in basic:
            remark = ''
        else:
            remark = basic['remark']
        tmp = {"project": project, 'remark': remark}
        result.append(tmp)
    return jsonify(result)


@app.route('/warrior_journey_event_action', methods=['POST'])
def warrior_journey_event_action():
    update_data = json.loads(request.data)

    result = {'msg': '成功', 'ret': 0}

    type = update_data['type']
    project = update_data['project']

    project_data = WarriorProj.query.filter_by(project=project).first()

    if type == 'clone':
        new_project_data = WarriorProj(basic=project_data.basic, localization=project_data.localization,
                                            calc_score=project_data.calc_score, reward=project_data.reward)

        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if (new_project_id is None):
            result = {'msg': '克隆失败', 'ret': 2}
        else:
            result = {'msg': '克隆成功', 'ret': 0}

    elif type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = WarriorProj.query.filter_by(
            project=project).first()
        if (new_project_data is None):
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}
    elif type == 'basic':
        result = {}
        doc_data = loadDocument()
        score_type_list = []
        mysql_data = WarriorJourneyEventScore.query.order_by(
            WarriorJourneyEventScore.doc_id).all()
        for p in mysql_data:
            id = int(p.id)
            num = str(p.num)
            doc_id = str(p.doc_id)
            doc_name = doc_data['doc_scoring_rule'][doc_id]['content'] + \
                "-" + str(doc_id)
            if 'STRING0' in doc_name:
                doc_name = doc_name.replace('STRING0', num)
            tmp = {"label": doc_name, 'value': id}
            score_type_list.append(tmp)

        result['score_type_list'] = score_type_list
        result['basic_data'] = json.loads(project_data.basic)
    elif type == 'remark':
        remark = update_data['remark']
        basic_data = json.loads(project_data.basic)
        basic_data['remark'] = remark
        WarriorProj.query.filter_by(project=project).update(
            {'basic': json.dumps(basic_data)})
        db.session.commit()

    elif type == 'update_basic':
        data = update_data['data']
        basic_data = json.dumps(data['basic_data'])
        WarriorProj.query.filter_by(project=project).update(
            {'basic': basic_data})

    elif type == 'user_goal':
        bonus_list = json.loads(project_data.reward)
        bonus_list = bonus_list['goal_reward']['user']
        result = RankGoalReward(bonus_list)
    elif type == 'alliance_goal':
        bonus_list = json.loads(project_data.reward)
        bonus_list = bonus_list['goal_reward']['alliance']
        result = RankGoalReward(bonus_list)
    elif type == 'serv_goal':
        bonus_list = json.loads(project_data.reward)
        bonus_list = bonus_list['goal_reward']['serv']
        result = RankGoalReward(bonus_list)
    elif type == 'update_user_goal':
        bonus_list = update_data['bonus']

        reward = json.loads(project_data.reward)
        reward['goal_reward']['user'] = UpdateRankGoalReward(bonus_list, 1)

        WarriorProj.query.filter_by(project=project).update(
            {'reward': json.dumps(reward)})

    elif type == 'update_alliance_goal':
        bonus_list = update_data['bonus']
        reward = json.loads(project_data.reward)
        reward['goal_reward']['alliance'] = UpdateRankGoalReward(bonus_list, 1)
        WarriorProj.query.filter_by(project=project).update(
            {'reward': json.dumps(reward)})

    elif type == 'update_serv_goal':
        bonus_list = update_data['bonus']
        reward = json.loads(project_data.reward)
        reward['goal_reward']['serv'] = UpdateRankGoalReward(bonus_list, 1)
        WarriorProj.query.filter_by(project=project).update(
            {'reward': json.dumps(reward)})

    return jsonify(result)


@app.route('/warrior_journey_down/<int:is_push>', methods=['GET', 'POST'])
def warrior_journey_down(is_push):

    mysql_data = WarriorJourneyEventScore.query.all()
    task_list = {}
    for p in mysql_data:
        id = int(p.id)
        type = int(p.type)
        score_type = list(map(int,p.score_type.split(",")))
        id_list = json.loads(p.id_list)
        num = int(p.num)
        score = int(p.score)
        doc_id = int(p.doc_id)
        task_list[str(id)] = {"type": type, "id_list": id_list,
                              "num": num, "score": score, "doc_id": doc_id, "score_type": score_type}

    result_data = {}
    project_data = WarriorProj.query.all()
    for p in project_data:
        project_id = str(p.project)
        basic = json.loads(p.basic)
        result_data[project_id] = {}
        result_data[project_id]['basic'] = {}
        result_data[project_id]['basic']['event_ui'] = int(basic['event_ui'])
        result_data[project_id]['basic']['is_kingdom'] = int(basic['is_kingdom'])

        reward = json.loads(p.reward)
        goal_reward = reward['goal_reward']
        name_list = ['user','alliance','serv']
        for n in range(len(name_list)):
            name = name_list[n]
            reward_data = goal_reward[name]
            for r in range(len(reward_data)):
                reward_data[r]['scene'] = int(reward_data[r]['from'])
                reward_data[r]['from'] = 1

        result_data[project_id]['reward'] = reward
        result_data[project_id]['localization'] = json.loads(p.localization)
        result_data[project_id]['extern0'] = {}
        result_data[project_id]['extern1'] = {}

        calc_score_list = []
        for i in range(len(basic['score_id_list'])):
            score_id = str(basic['score_id_list'][i])
            calc_score_list.append(task_list[score_id])

        result_data[project_id]['calc_score'] = {}
        result_data[project_id]['calc_score']['score_type_list'] = calc_score_list
    result_data['event_main_type'] = 73

    response = DownLoad('warrior_journey_event_project', result_data, is_push)

    return response


@app.route('/lost_achievenemt_action_config', methods=['POST'])
def lost_achievenemt_action_config():
    update_data = json.loads(request.data)
    result = {'msg': '成功', 'ret': 0}
    type = update_data['type']
    if type == 'init':
        name = int(update_data['name'])
        result = {}
        mysql_data = LostAchievenemtAction.query.order_by(
            LostAchievenemtAction.doc_id).all()
        task_list = []
        for p in mysql_data:
            id = int(p.id)
            # score_type = list(map(int,p.score_type.split(",")))
            score_type = int(p.score_type)
            if name != score_type:
                continue
            type = int(p.type)
            id_list = json.loads(p.id_list)
            num = int(p.num)
            score = int(p.score)
            doc_id = int(p.doc_id)
            add_type = int(p.add_type)
            tmp = {'id': id, 'id_list': id_list, 'num': num,
                   'score': score, 'doc_id': doc_id, 'task_type': type, 'score_type': score_type, 'add_type':add_type}
            task_list.append(tmp)
        result = score_type_list()
        doc_id_list = copy.deepcopy(result['doc_id_list'])
        task_type_list = copy.deepcopy(result['task_type_list'])
        new_doc_id_list = []
        new_task_type_list = []
        for x in range(len(doc_id_list)):
            id = doc_id_list[x]['value']
            if id >= 293:
                new_doc_id_list.append(doc_id_list[x])
        tmp_type_id_list = {"0":[81,82,88,83],"1":[83,91,92],"2":[83,91]}
        for x in range(len(task_type_list)):
            id = task_type_list[x]['value']
            if id in tmp_type_id_list[str(name)]:
                new_task_type_list.append(task_type_list[x])
        result['doc_id_list'] = new_doc_id_list
        result['task_type_list'] = new_task_type_list
        result['task_list'] = task_list
        return jsonify(result)
    elif type == 'delete':
        id = update_data['id']
        project_data = LostAchievenemtAction.query.filter_by(id=id).first()
        db.session.delete(project_data)
        db.session.commit()
        project_data = LostAchievenemtAction.query.filter_by(id=id).first()
        if (project_data is None):
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}
        return jsonify(result)
    elif type == 'update':
        task_list = update_data['task_list']
        for x in range(len(task_list)):
            task = task_list[x]
            id = int(task['id'])
            # score_type = ','.join(list(map(str,task['score_type'])))
            score_type = int(task['score_type'])
            task_type = int(task['task_type'])
            id_list = json.dumps(task['id_list'])
            num = int(task['num'])
            score = int(task['score'])
            doc_id = int(task['doc_id'])
            # add_type = int(task['add_type'])
            if task_type == 91:
                add_type = 1
            else:
                add_type = 0

            if id == -1:
                mysql_data = LostAchievenemtAction(
                    id_list=id_list, score=score, num=num, doc_id=doc_id, type=task_type, score_type=score_type, add_type=add_type)
                db.session.add(mysql_data)
                db.session.commit()
            else:
                LostAchievenemtAction.query.filter_by(id=id).update(
                    {'type': task_type, 'id_list': id_list, 'score': score, 'num': num, 'doc_id': doc_id, 'score_type': score_type, 'add_type':add_type})
                db.session.commit()

        return jsonify({'msg': '更新成功', 'ret': 0})

@app.route('/lost_achievenemt_honor_config', methods=['POST'])
def lost_achievenemt_honor_config():
    update_data = json.loads(request.data)
    result = {'msg': '成功', 'ret': 0}
    type = update_data['type']
    if type == 'init':
        name = int(update_data['name'])
        result = {}
        mysql_data = LostAchievenemtHonor.query.order_by(
            LostAchievenemtHonor.doc_id).all()
        task_list = []
        for p in mysql_data:
            id = int(p.id)
            score_type = list(map(int,p.score_type.split(",")))
            if name not in score_type:
                continue
            type = int(p.type)
            id_list = json.loads(p.id_list)
            num = int(p.num)
            score = int(p.score)
            doc_id = int(p.doc_id)
            if type in [84,85,86,87]:
                flag = True
            else:
                flag = False
            tmp = {'id': id, 'id_list': id_list, 'num': num,
                   'score': score, 'doc_id': doc_id, 'task_type': type, 'score_type': score_type,'flag':flag}
            task_list.append(tmp)
        result = score_type_list()
        doc_id_list = copy.deepcopy(result['doc_id_list'])
        task_type_list = copy.deepcopy(result['task_type_list'])
        new_doc_id_list = []
        new_task_type_list = []
        for x in range(len(doc_id_list)):
            id = doc_id_list[x]['value']
            if id >= 293:
                new_doc_id_list.append(doc_id_list[x])
        tmp_type_id_list = {"0":[88,89,93],"1":[84,86,88,90,93],"2":[85,87,88,90,93]}
        for x in range(len(task_type_list)):
            id = task_type_list[x]['value']
            if id in tmp_type_id_list[str(name)]:
                new_task_type_list.append(task_type_list[x])
        result['doc_id_list'] = new_doc_id_list
        result['task_type_list'] = new_task_type_list
        result['task_list'] = task_list
        return jsonify(result)
    elif type == 'delete':
        id = update_data['id']
        project_data = LostAchievenemtHonor.query.filter_by(id=id).first()
        db.session.delete(project_data)
        db.session.commit()
        project_data = LostAchievenemtHonor.query.filter_by(id=id).first()
        if (project_data is None):
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}
        return jsonify(result)
    elif type == 'update':
        task_list = update_data['task_list']
        for x in range(len(task_list)):
            task = task_list[x]
            id = int(task['id'])
            score_type = ','.join(list(map(str,task['score_type'])))
            task_type = int(task['task_type'])
            id_list = json.dumps(task['id_list'])
            if int(task_type) == 93:
                num = int(task['num'])
            else:
                num = 1
            score = int(task['score'])
            doc_id = int(task['doc_id'])
            if id == -1:
                mysql_data = LostAchievenemtHonor(
                    id_list=id_list, score=score, num=num, doc_id=doc_id, type=task_type, score_type=score_type)
                db.session.add(mysql_data)
                db.session.commit()
            else:
                LostAchievenemtHonor.query.filter_by(id=id).update(
                    {'type': task_type, 'id_list': id_list, 'score': score, 'num': num, 'doc_id': doc_id, 'score_type': score_type})
                db.session.commit()

        return jsonify({'msg': '更新成功', 'ret': 0})

@app.route('/lost_achievenemt_event', methods=['GET'])
def lost_achievenemt_event():
    data = LostAchievenemtProj.query.all()
    result = []
    for d in data:
        project = int(d.project)
        basic = json.loads(d.basic)
        if 'remark' not in basic:
            remark = ''
        else:
            remark = basic['remark']
        tmp = {"project": project, 'remark': remark}
        result.append(tmp)
    return jsonify(result)

@app.route('/lost_achievenemt_action', methods=['POST'])
def lost_achievenemt_action():
    update_data = json.loads(request.data)

    result = {'msg': '成功', 'ret': 0}

    type = update_data['type']
    project = update_data['project']

    project_data = LostAchievenemtProj.query.filter_by(project=project).first()

    if type == 'clone':
        new_project_data = LostAchievenemtProj(basic=project_data.basic, localization=project_data.localization,
                                            task=project_data.task, reward=project_data.reward)

        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if (new_project_id is None):
            result = {'msg': '克隆失败', 'ret': 2}
        else:
            result = {'msg': '克隆成功', 'ret': 0}

    elif type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = LostAchievenemtProj.query.filter_by(
            project=project).first()
        if (new_project_data is None):
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}
    elif type == 'basic':
        result = {}
        doc_data = loadDocument()
        score_type_list = []
        mysql_data = LostAchievenemtHonor.query.order_by(
            LostAchievenemtHonor.doc_id).all()
        for p in mysql_data:
            id = int(p.id)
            num = str(p.num)
            doc_id = str(p.doc_id)
            doc_name = doc_data['doc_scoring_rule'][doc_id]['content'] + \
                "-" + str(doc_id)
            if 'STRING0' in doc_name:
                doc_name = doc_name.replace('STRING0', num)
            tmp = {"label": doc_name, 'value': id}
            score_type_list.append(tmp)

        result['score_type_list'] = score_type_list
        result['basic_data'] = json.loads(project_data.basic)
    elif type == 'remark':
        remark = update_data['remark']
        basic_data = json.loads(project_data.basic)
        basic_data['remark'] = remark
        LostAchievenemtProj.query.filter_by(project=project).update(
            {'basic': json.dumps(basic_data)})
        db.session.commit()

    elif type == 'update_basic':
        data = update_data['data']
        basic_data = json.dumps(data['basic_data'])
        LostAchievenemtProj.query.filter_by(project=project).update(
            {'basic': basic_data})

    elif type == 'user_goal':
        bonus_list = json.loads(project_data.reward)
        bonus_list = bonus_list['rank_reward']['user']
        result = RankGoalReward(bonus_list)
    elif type == 'alliance_goal':
        bonus_list = json.loads(project_data.reward)
        bonus_list = bonus_list['rank_reward']['alliance']
        result = RankGoalReward(bonus_list)
    elif type == 'serv_goal':
        bonus_list = json.loads(project_data.reward)
        bonus_list = bonus_list['rank_reward']['svr']
        result = RankGoalReward(bonus_list)
    elif type == 'update_user_goal':
        bonus_list = update_data['bonus']

        reward = json.loads(project_data.reward)
        reward['rank_reward']['user'] = UpdateRankGoalReward(bonus_list, 1)

        LostAchievenemtProj.query.filter_by(project=project).update(
            {'reward': json.dumps(reward)})

    elif type == 'update_alliance_goal':
        bonus_list = update_data['bonus']
        reward = json.loads(project_data.reward)
        reward['rank_reward']['alliance'] = UpdateRankGoalReward(bonus_list, 1)
        LostAchievenemtProj.query.filter_by(project=project).update(
            {'reward': json.dumps(reward)})

    elif type == 'update_serv_goal':
        bonus_list = update_data['bonus']
        reward = json.loads(project_data.reward)
        reward['rank_reward']['svr'] = UpdateRankGoalReward(bonus_list, 1)
        LostAchievenemtProj.query.filter_by(project=project).update(
            {'reward': json.dumps(reward)})
    elif type == 'task':

        name = update_data['name']

        task_data = json.loads(project_data.task)

        task_list = []
        if str(name) in task_data:
            task_list = task_data[name]
            for x in range(len(task_list)):
                if task_list[x]['task_type'] != int(name):
                    continue
                task_list[x]['id'] = x
                task_list[x]['reward'] = RewardToDic(task_list[x]['task_reward'])[0]

                action = task_list[x]['action']
                task_list[x]['action_id'] = []
                task_list[x]['action_score'] = []
                if len(action) != 0:
                    for a in range(len(action)):
                        task_list[x]['action_id'].append(action[a][0])
                        task_list[x]['action_score'].append(action[a][1])
                    task_list[x]['action_score'] = ','.join(list(map(str,task_list[x]['action_score'])))
                else:
                    task_list[x]['action_id'] = []
                    task_list[x]['action_score'] = ''


                honor = task_list[x]['honor']
                task_list[x]['honor_id'] = []
                task_list[x]['honor_score'] = []
                if len(honor) != 0:
                    for h in range(len(honor)):
                        task_list[x]['honor_id'].append(honor[h][0])
                        task_list[x]['honor_score'].append(honor[h][1])
                    task_list[x]['honor_score'] = ','.join(list(map(str,task_list[x]['honor_score'])))
                else:
                    task_list[x]['honor_id'] = []
                    task_list[x]['honor_score'] = ''

        doc_data = loadDocument()
        action_id_list = []
        mysql_data = LostAchievenemtAction.query.order_by(
            LostAchievenemtAction.doc_id).all()
        for p in mysql_data:
            # score_type = list(map(int,p.score_type.split(",")))
            score_type = int(p.score_type)
            if int(name) != score_type:
                continue
            id = int(p.id)
            num = str(p.num)
            doc_id = str(p.doc_id)
            doc_name = doc_data['doc_scoring_rule'][doc_id]['content'] + \
                "-" + str(doc_id)
            if 'STRING0' in doc_name:
                doc_name = doc_name.replace('STRING0', num)
            tmp = {"label": doc_name, 'value': id}
            action_id_list.append(tmp)

        result['task_list'] = task_list
        result['action_id_list'] = action_id_list

    elif type == 'update_task':
        name = update_data['name']
        task_list = update_data['task_list']
        for x in range(len(task_list)):
            if 'id' in task_list[x]:
                del task_list[x]['id']

            action_id = copy.deepcopy(task_list[x]['action_id'])

            if len(action_id) != 0 and task_list[x]['action_score'] == '':
                return jsonify({'msg': 'action id != action score', 'ret': 1})
            elif len(action_id) == 0 and task_list[x]['action_score'] != '':
                return jsonify({'msg': 'action id != action score', 'ret': 1})
            else:
                pass
            if len(action_id) != 0:
                action_score = list(map(int, task_list[x]['action_score'].split(",")))
                if len(action_id) != len(action_score):
                    return jsonify({'msg': 'action id != action score', 'ret': 1})
                task_list[x]['action'] = []
                for a in range(len(action_id)):
                    tmp = [int(action_id[a]),int(action_score[a])]
                    task_list[x]['action'].append(tmp)
            else:
                task_list[x]['action'] = []


            honor_id = copy.deepcopy(task_list[x]['honor_id'])
            if len(honor_id) != 0 and task_list[x]['honor_score'] == '':
                return jsonify({'msg': 'honor id != honor score', 'ret': 1})
            elif len(honor_id) == 0 and task_list[x]['honor_score'] != '':
                return jsonify({'msg': 'honor id != honor score', 'ret': 1})
            else:
                pass

            if len(honor_id) != 0:
                honor_score = list(map(int, task_list[x]['honor_score'].split(",")))
                if len(honor_id) != len(honor_score):
                    return jsonify({'msg': 'honor id != honor score', 'ret': 1})
                task_list[x]['honor'] = []
                for a in range(len(honor_id)):
                    tmp = [int(honor_id[a]),int(honor_score[a])]
                    task_list[x]['honor'].append(tmp)
            else:
                task_list[x]['honor'] = []

            task_list[x]['task_type'] = int(name)
            task_list[x]['doc_id'] = 1

            reward = task_list[x]['reward']['reward']
            new_reward = []
            for r in range(len(reward)):
                tmp = {}
                tmp['a'] = [int(reward[r]['type']),reward[r]['id'],reward[r]['num']]
                new_reward.append(tmp)
            task_list[x]['task_reward'] = new_reward

        task_data = json.loads(project_data.task)
        task_data[name] = task_list

        LostAchievenemtProj.query.filter_by(project=project).update({'task':json.dumps(task_data)})
        db.session.commit()

    return jsonify(result)


@app.route('/lost_achievenemt_down/<int:is_push>', methods=['GET', 'POST'])
def lost_achievenemt_down(is_push):

    mysql_data = LostAchievenemtAction.query.all()
    action_task_list = {}
    for p in mysql_data:
        id = int(p.id)
        type = int(p.type)
        # score_type = list(map(int,p.score_type.split(",")))
        score_type = int(p.score_type)
        id_list = json.loads(p.id_list)
        num = int(p.num)
        score = int(p.score)
        doc_id = int(p.doc_id)
        add_type = int(p.add_type)
        action_task_list[str(id)] = {"detail": [type,num,score], "id_list": id_list,"doc_id": doc_id, "score_type": score_type,"add_type": add_type}

    mysql_data = LostAchievenemtHonor.query.all()
    honor_task_list = {}
    for p in mysql_data:
        id = int(p.id)
        type = int(p.type)
        score_type = list(map(int,p.score_type.split(",")))
        id_list = json.loads(p.id_list)
        num = int(p.num)
        score = int(p.score)
        doc_id = int(p.doc_id)
        tmp = {"type": type, "id_list": id_list,"num": num,"score": score,"doc_id": doc_id, "score_type": score_type}
        honor_task_list[str(id)] = tmp

    result_data = {}
    project_data = LostAchievenemtProj.query.all()
    for p in project_data:
        project_id = str(p.project)
        basic = json.loads(p.basic)
        task = json.loads(p.task)
        result_data[project_id] = {}
        result_data[project_id]['basic'] = {}
        result_data[project_id]['basic']['event_ui'] = int(basic['event_ui'])
        result_data[project_id]['reward'] = json.loads(p.reward)
        result_data[project_id]['localization'] = json.loads(p.localization)
        result_data[project_id]['task'] = []
        for x in task:
            for y in range(len(task[x])):
                del task[x][y]['action_score']
                del task[x][y]['action_id']
                del task[x][y]['honor_score']
                del task[x][y]['honor_id']
                del task[x][y]['reward']
                result_data[project_id]['task'].append(task[x][y])

        new_honor_task_list = []
        score_id_list = basic['score_id_list']
        for s in range(len(score_id_list)):
            sid = str(score_id_list[s])
            new_honor_task_list.append(honor_task_list[sid])

        result_data[project_id]['action'] = action_task_list
        result_data[project_id]['honor'] = {}
        result_data[project_id]['honor']['score_type_list'] = new_honor_task_list

        result_data[project_id]['extern0'] = {}
        result_data[project_id]['extern1'] = {}

    result_data['event_main_type'] = 74

    response = DownLoad('lost_achievenemt_event_project', result_data, is_push)

    return response

@app.route('/multi_growth_gift_project', methods=['GET'])
def multi_growth_gift_project():
    data = MultiGrowthGiftProject.query.all()
    result = []
    for d in data:
        project = int(d.project)
        tmp = {"project": project, 'remark': d.remark}
        result.append(tmp)
    return jsonify(result)

@app.route('/multi_growth_gift_project_action', methods=['POST'])
def multi_growth_gift_project_action():
    update_data = json.loads(request.data)

    result = {'msg': '成功', 'ret': 0}

    type = update_data['type']
    project = update_data['project']

    project_data = MultiGrowthGiftProject.query.filter_by(project=project).first()

    if type == 'clone':
        new_project_data = MultiGrowthGiftProject(basic_data=project_data.basic_data, localization=project_data.localization,
                                            level_task_list=project_data.level_task_list, remark=project_data.remark)

        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if (new_project_id is None):
            result = {'msg': '克隆失败', 'ret': 2}
        else:
            result = {'msg': '克隆成功', 'ret': 0}

    elif type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = MultiGrowthGiftProject.query.filter_by(
            project=project).first()
        if (new_project_data is None):
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}
    elif type == 'basic':
        result = {}

        reward_item_list = rewardList()['name']
        level_task_list = json.loads(project_data.level_task_list)
        for idx, node in enumerate(level_task_list):
            node['reward'] = RewardShowToDoc(node['reward'], reward_item_list)
            node['id'] = idx
        result['basic_data'] = json.loads(project_data.basic_data)
        result['level_task_list'] = level_task_list
    elif type == 'remark':
        remark = update_data['remark']
        MultiGrowthGiftProject.query.filter_by(project=project).update({'remark': remark})
        db.session.commit()
    elif type == 'update_basic':
        basic_data = update_data['basic_data']
        level_task_list = update_data['level_task_list']
        for node in level_task_list:
            node['reward'] = RewardToTMysqlNew(node['reward'])
            del node['id']

        MultiGrowthGiftProject.query.filter_by(project=project).update({'basic_data': json.dumps(basic_data), 'level_task_list':json.dumps(level_task_list)})

    return jsonify(result)


@app.route('/multi_growth_gift_project_down/<int:is_push>', methods=['GET', 'POST'])
def multi_growth_gift_project_down(is_push):

    result_data = {}
    project_data = MultiGrowthGiftProject.query.all()
    for p in project_data:
        project_id = str(p.project)
        result_data[project_id] = {}
        result_data[project_id]['basic_data'] = json.loads(p.basic_data)
        result_data[project_id]['localization'] = json.loads(p.localization)
        result_data[project_id]['level_task_list'] = json.loads(p.level_task_list)

    response = DownLoad('multi_growth_gift_project', result_data, is_push)
    return response


@app.route('/zhengduo_project', methods=['GET'])
def zhengduo_project():
    zhengduo_query = ZhengDuoProject.query.order_by('project').all()
    result = []
    for que in zhengduo_query:
        tmp = {'project': que.project, 'remark': que.remark}
        result.append(tmp)
    return jsonify(result)

@app.route('/zhengduo_project_action', methods=['GET', 'POST'])
def zhengduo_project_action():
    update_data = json.loads(request.data)
    result = {'msg': '成功','ret':0}
    _type = update_data['type']
    project = update_data['project']
    project_data = ZhengDuoProject.query.filter_by(project=project).first()

    if _type == 'remark':
        remark = update_data['remark']
        project_data.remark = remark
        db.session.commit()

    elif _type == 'clone':
        new_project_data = ZhengDuoProject(main=project_data.main,
                                           localization=project_data.localization,
                                           achievement=project_data.achievement,
                                           alliance_config=project_data.alliance_config,
                                           remark=project_data.remark)
        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if (new_project_id is None):
            result = {'msg': '克隆失败','ret':2}
        else:
            result = {'msg': '克隆成功','ret':0}

    elif _type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = ZhengDuoProject.query.filter_by(project=project).first()
        if (new_project_data is None):
            result = {'msg': '删除成功','ret':0}
        else:
            result = {'msg': '删除失败','ret':1}

    elif _type == 'basic':
        result = {}
        # buliding_list = [{'building_id': 0, 'building_name': '圣殿'},
        #                  {'building_id': 1, 'building_name': '圣殿'}]
        task_type_list = [
            {'label': '联盟持续占领(至少以m个士兵驻守)', 'type': 0},
            {'label': '联盟完全占领', 'type': 1},
            {'label': '所有联盟成员每共同造成x个敌方联盟玩家的Tn士兵受伤', 'type': 2},
            {'label': '所有联盟成员每共有X个Tn士兵受伤', 'type': 3}]
        buliding_list = GetBuildingIdList()

        basic_data = json.loads(project_data.main)
        result['buliding_list'] = buliding_list
        result['task_type_list'] = task_type_list
        result['basic_data'] = basic_data

    elif _type == 'update_basic':
        basic_data = update_data['data_list']
        project_data.main = json.dumps(basic_data)
        db.session.commit()

    elif _type == 'achievement':
        standard = json.loads(project_data.standard) if project_data.standard else []
        special = json.loads(project_data.special)if project_data.special else []
        result['standard'] = standard
        result['special'] = special

        result['building_id_list'] = GetBuildingIdList()

    elif _type == 'update_achievement':
        standard = update_data['standard']
        special = update_data['special']
        project_data.standard = json.dumps(standard)
        project_data.special = json.dumps(special)
        db.session.commit()

    elif _type == 'alliance_config':
        result = {}

        building_id_list = GetBuildingIdList()

        alliance_config = json.loads(project_data.alliance_config)
        for i in range(1, 13):
            if str(i) not in alliance_config.keys():
                alliance_config[str(i)] = {'reward': []}
        result['alliance_config'] = alliance_config
        result['building_id_list'] = building_id_list

    elif _type == 'update_alliance_config':
        alliance_config = update_data['alliance_config']
        project_data.alliance_config = json.dumps(alliance_config)
        db.session.commit()

    return jsonify(result)

@app.route('/zhengduo_project_download/<int:is_push>', methods=['GET', 'POST'])
def zhengduo_project_download(is_push):
    result_data = {}
    project_data = ZhengDuoProject.query.all()
    for p in project_data:
        project_id = str(p.project)
        result_data[project_id] = {}
        main = json.loads(p.main)
        for node in main:
            if 'index' in node.keys():
                del node['index']

        standard = json.loads(p.standard)
        special = json.loads(p.special)
        for node in special:
            if 'index' in node.keys():
                del node['index']
            node['reward'] = RewardToTMysqlNew(node['reward'])

        alliance_config = json.loads(p.alliance_config)
        for k, node in alliance_config.items():
            if 'reward' in node.keys():
                if len(node['reward']) == 0 and 'limit' not in node.keys():
                    del node['reward']
                    continue
                for reward_node in node['reward']:
                    if 'index' in reward_node.keys():
                        del reward_node['index']
                    reward_node['reward'] = RewardToTMysqlNew(reward_node['reward'])
                    for special_reward_node in reward_node['special_reward']:
                        special_reward_node['reward'] = RewardToTMysqlNew(special_reward_node['reward'])

        result_data[project_id]['main'] = main
        result_data[project_id]['achievement'] = {'standard': standard, 'special': special}
        result_data[project_id]['localization'] = json.loads(p.localization)
        result_data[project_id]['alliance_config'] = alliance_config

    response = DownLoad('zhengduo_project', result_data, is_push)
    return response


@app.route('/mubiaoxing_project', methods=['GET'])
def mubiaoxing_project():
    query = MuBiaoXingProject.query.order_by('project').all()
    result = []
    for que in query:
        tmp = {'project': que.project, 'remark': que.remark}
        result.append(tmp)
    return jsonify(result)

@app.route('/mubiaoxing_project_action', methods=['GET', 'POST'])
def mubiaoxing_project_action():
    update_data = json.loads(request.data)
    result = {'msg': '成功','ret':0}
    _type = update_data['type']
    project = update_data['project']
    project_data = MuBiaoXingProject.query.filter_by(project=project).first()

    if _type == 'remark':
        project_data.remark = update_data['remark']
        db.session.commit()

    elif _type == 'clone':
        new_project_data = MuBiaoXingProject(basic=project_data.basic,
                                             task=project_data.task,
                                             remark=project_data.remark,
                                             localization=project_data.localization)
        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if (new_project_id is None):
            result = {'msg': '克隆失败','ret':2}
        else:
            result = {'msg': '克隆成功','ret':0}

    elif _type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = MuBiaoXingProject.query.filter_by(project=project).first()
        if (new_project_data is None):
            result = {'msg': '删除成功','ret':0}
        else:
            result = {'msg': '删除失败','ret':1}

    elif _type == 'basic':
        result = {}
        result['basic_data'] = json.loads(project_data.basic)
        result['task'] = json.loads(project_data.task)

    elif _type == 'update_basic':
        basic = update_data['data_list']
        task = update_data['task_list']
        for i in range(len(task)):
            node = task[i]
            node['task_id'] = 100*(project+1) + i
        project_data.basic = json.dumps(basic)
        project_data.task = json.dumps(task)
        db.session.commit()

    return jsonify(result)

@app.route('/mubiaoxing_project_download/<int:is_push>', methods=['GET', 'POST'])
def mubiaoxing_project_download(is_push):
    result_data = {}
    project_data = MuBiaoXingProject.query.all()
    for que in project_data:
        project = que.project
        basic = json.loads(que.basic)
        task = json.loads(que.task)
        localization = json.loads(que.localization)
        for i in range(len(task)):
            node = task[i]
            if 'id' in node.keys():
                del node['id']
            if 'tmp_id' in node.keys():
                node['id_list'] = [node['tmp_id']]
                del node['tmp_id']
            node['reward'] = RewardToTMysqlNew(node['reward'])
            node['task_id'] = 100*(project+1) + i
        result_data[project] = {'basic': basic, 'task': task,
                           'localization': localization}

    response = DownLoad('mubiaoxing_project', result_data, is_push)
    return response


@app.route('/xingeren_project', methods=['GET'])
def xingeren_project():
    query = XinGeRenProject.query.order_by('project').all()
    result = []
    for que in query:
        localization = json.loads(que.localization)
        title = localization['title']['0'] if 'title' in localization.keys() else ''
        tmp = {'project': que.project, 'remark': que.remark, 'title': title}
        result.append(tmp)
    return jsonify(result)

@app.route('/xingeren_project_action', methods=['GET', 'POST'])
def xingeren_project_action():
    update_data = json.loads(request.data)
    result = {'msg': '成功','ret':0}
    _type = update_data['type']
    project = update_data['project']
    project_data = XinGeRenProject.query.filter_by(project=project).first()

    if _type == 'remark':
        project_data.remark = update_data['remark']
        db.session.commit()

    elif _type == 'clone':
        new_project_data = XinGeRenProject(basic=project_data.basic,
                                           task=project_data.task,
                                           localization=project_data.localization,
                                           goal_reward=project_data.goal_reward,
                                           rank_reward=project_data.rank_reward,
                                           remark=project_data.remark)
        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if (new_project_id is None):
            result = {'msg': '克隆失败','ret':2}
        else:
            result = {'msg': '克隆成功','ret':0}

    elif _type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = XinGeRenProject.query.filter_by(project=project).first()
        if (new_project_data is None):
            result = {'msg': '删除成功','ret':0}
        else:
            result = {'msg': '删除失败','ret':1}

    elif _type == 'basic':
        result = {}
        result['basic_data'] = json.loads(project_data.basic)
        result['task'] = json.loads(project_data.task)

    elif _type == 'update_basic':
        basic = update_data['data_list']
        task = update_data['task_list']
        project_data.basic = json.dumps(basic)
        project_data.task = json.dumps(task)
        db.session.commit()

    elif _type == 'goal_reward':
        result = {}
        result['goal_reward'] = json.loads(project_data.goal_reward)

    elif _type == 'update_goal_reward':
        goal_reward = update_data['data_list']
        project_data.goal_reward = json.dumps(goal_reward)
        db.session.commit()

    elif _type == 'rank_reward':
        result = {}
        result['rank_limit'] = project_data.rank_limit
        result['rank_reward'] = json.loads(project_data.rank_reward)

    elif _type == 'update_rank_reward':
        rank_reward = update_data['data_list']
        rank_limit = update_data['rank_limit']
        project_data.rank_reward = json.dumps(rank_reward)
        project_data.rank_limit = rank_limit
        db.session.commit()

    return jsonify(result)

@app.route('/xingeren_project_download/<int:is_push>', methods=['GET', 'POST'])
def xingeren_project_download(is_push):
    result_data = {}
    project_data = XinGeRenProject.query.all()
    for que in project_data:
        project = que.project
        basic = json.loads(que.basic)
        task = json.loads(que.task)
        localization = json.loads(que.localization)
        goal_reward = json.loads(que.goal_reward)
        rank_reward = json.loads(que.rank_reward)
        rank_limit = que.rank_limit
        for i in range(len(task)):
            node = task[i]
            if 'index' in node.keys():
                del node['index']
            if 'tmp_id' in node.keys():
                node['id_list'] = [node['tmp_id']]
                del node['tmp_id']
            node['task_id'] = (project + 1) * 100 + 1

        for node in goal_reward:
            if 'index' in node.keys():
                del node['index']
            node['reward'] = RewardToTMysqlNew(node['reward'])
        for node in rank_reward:
            if 'index' in node.keys():
                del node['index']
            node['reward'] = RewardToTMysqlNew(node['reward'])

        result_data[project] = {'basic': basic, 'task': task,
                                'localization': localization,
                                'goal_reward': goal_reward,
                                'rank_reward': rank_reward,
                                'rank_limit': rank_limit}

    response = DownLoad('xingeren_project', result_data, is_push)
    return response


@app.route('/backflow_main_proj', methods=['GET'])
def backflow_main_proj():
    query = BackflowMainProj.query.order_by('project').all()
    result = []
    for que in query:
        basic = json.loads(que.basic)
        # tmp = {'project': que.project, 'remark': que.remark, 'event_type': basic['event_type']}
        tmp = {'project': que.project, 'remark': que.remark}
        result.append(tmp)
    return jsonify(result)

@app.route('/backflow_main_proj_action', methods=['GET', 'POST'])
def backflow_main_proj_action():
    update_data = json.loads(request.data)
    result = {'msg': '成功','ret':0}
    _type = update_data['type']
    project = update_data['project']
    project_data = BackflowMainProj.query.filter_by(project=project).first()

    if _type == 'remark':
        project_data.remark = update_data['remark']
        db.session.commit()

    elif _type == 'clone':
        new_project_data = BackflowMainProj(
            basic=project_data.basic,
            login_reward=project_data.login_reward,
            task_group=project_data.task_group,
            consume_group=project_data.consume_group,
            iap_group=project_data.iap_group,
            remark=project_data.remark,
            score_reward=project_data.score_reward,
            main_localization=project_data.main_localization,
            login_localization=project_data.login_localization,
            consume_localization=project_data.consume_localization,
            task_localization=project_data.task_localization,
            iap_localization=project_data.iap_localization,
            task_doc_localization=project_data.task_doc_localization,
            day_doc_localization=project_data.day_doc_localization,
            migration_localization=project_data.migration_localization,
            benefits=project_data.benefits,
            new_journey=project_data.new_journey,
            multiday_recharge=project_data.multiday_recharge,
            store_treasure=project_data.store_treasure,
            inheritance=project_data.inheritance,
            new_journey_login_reward=project_data.new_journey_login_reward,
            new_journey_task_group=project_data.new_journey_task_group,
            new_journey_score_reward=project_data.new_journey_score_reward,
            new_journey_iap_group=project_data.new_journey_iap_group,
            new_journey_multiday_recharge=project_data.new_journey_multiday_recharge,
            new_journey_store_treasure=project_data.new_journey_store_treasure
        )
        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if (new_project_id is None):
            result = {'msg': '克隆失败','ret':2}
        else:
            result = {'msg': '克隆成功','ret':0}

    elif _type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = BackflowMainProj.query.filter_by(project=project).first()
        if (new_project_data is None):
            result = {'msg': '删除成功','ret':0}
        else:
            result = {'msg': '删除失败','ret':1}

    elif _type == 'basic':
        result = {}
        basic = json.loads(project_data.basic)
        basic_data = {
            'castle_lv': basic['castle_lv'],
            'offline_day': basic['offline_day'],
            'doc_id': basic['doc_id'],
            'new_journey_doc_id': basic['new_journey_doc_id'],
            # 'event_type': basic['event_type'],
            'cd': basic['cd'],
            'cd_unit': basic['cd_unit'],
            'open_control': basic['open_control']
        }
        result['basic_data'] = basic_data

    elif _type == 'update_basic':
        basicData = update_data['data']
        basic = basicData['basic_data']
        basic_data = json.loads(project_data.basic)
        basic_data['castle_lv'] = int(basic['castle_lv'])
        basic_data['offline_day'] = int(basic['offline_day'])
        basic_data['doc_id'] = int(basic['doc_id'])
        basic_data['new_journey_doc_id'] = int(basic['new_journey_doc_id'])
        # basic_data['event_type'] = int(basic['event_type'])
        basic_data['cd'] = int(basic['cd'])
        basic_data['cd_unit'] = basic['cd_unit']
        basic_data['open_control'] = basic['open_control']
        project_data.basic = json.dumps(basic_data)
        db.session.commit()

    elif _type == 'new_login_reward':
        login_reward = json.loads(project_data.login_reward)
        for i in range(0, 8):
            if str(i) not in login_reward:
                login_reward[str(i)] = []

        doc_card_list = []
        selected_card_list = []
        with open(GLOBAL_PATH + 'document_english.json', encoding='utf-8') as f:
            content = json.load(f)['doc_card_medal']

        for x in login_reward['7']:
            tmp = {'label': content[str(x)]['name'] + '--' + str(x),
                   'value': int(x)}
            selected_card_list.append(tmp)

        new_login_reward = []
        for i in range(0, 8):
            if i != 7:
                new_login_reward.append({'reward': login_reward[str(i)],
                                         'index': i, 'name': '第{}天'.format(i+1)})
            else:
                new_login_reward.append({'reward': login_reward['7'],
                                         'index': i, 'name': '第{}天'.format(i+1)})

        for k, v in content.items():
            if 'Omnipotent' in v['name']:
                continue
            tmp = {'value': int(k), 'label': v['name'] + '--' + k}
            doc_card_list.append(tmp)

        basic = json.loads(project_data.basic)

        result['login_reward'] = new_login_reward
        result['doc_card_list'] = doc_card_list
        result['selected_card_list'] = selected_card_list

    elif _type == 'update_new_login_reward':
        login_reward = update_data['data']
        new_login_reward = {}
        for i in range(len(login_reward)):
            new_login_reward[str(i)] = login_reward[i]['reward']

        project_data.login_reward = json.dumps(new_login_reward)
        db.session.commit()

    elif _type == 'new_journey_new_login_reward':
        login_reward = json.loads(project_data.new_journey_login_reward)
        for i in range(0, 8):
            if str(i) not in login_reward:
                login_reward[str(i)] = []

        doc_card_list = []
        selected_card_list = []
        with open(GLOBAL_PATH + 'document_english.json', encoding='utf-8') as f:
            content = json.load(f)['doc_card_medal']

        for x in login_reward['7']:
            tmp = {'label': content[str(x)]['name'] + '--' + str(x),
                   'value': int(x)}
            selected_card_list.append(tmp)

        new_login_reward = []
        for i in range(0, 8):
            if i != 7:
                new_login_reward.append({'reward': login_reward[str(i)],
                                         'index': i, 'name': '第{}天'.format(i+1)})
            else:
                new_login_reward.append({'reward': login_reward['7'],
                                         'index': i, 'name': '第{}天'.format(i+1)})

        for k, v in content.items():
            if 'Omnipotent' in v['name']:
                continue
            tmp = {'value': int(k), 'label': v['name'] + '--' + k}
            doc_card_list.append(tmp)

        basic = json.loads(project_data.basic)

        result['login_reward'] = new_login_reward
        result['doc_card_list'] = doc_card_list
        result['selected_card_list'] = selected_card_list

    elif _type == 'update_new_journey_new_login_reward':
        login_reward = update_data['data']
        new_login_reward = {}
        for i in range(len(login_reward)):
            new_login_reward[str(i)] = login_reward[i]['reward']

        project_data.new_journey_login_reward = json.dumps(new_login_reward)
        db.session.commit()

    elif _type == 'login_reward':
        # 英雄ID type == 58
        login_reward = json.loads(project_data.login_reward)
        for i in range(0, 8):
            if str(i) not in login_reward:
                login_reward[str(i)] = []
        doc_card_list = []
        selected_card_list = []
        with open(GLOBAL_PATH + 'document_english.json', encoding='utf-8') as f:
            content = json.load(f)['doc_card']

        for x in login_reward['7']:
            tmp = {'label': content[str(x)]['name'] + '--' + str(x),
                   'value': int(x)}
            selected_card_list.append(tmp)
        if len(login_reward['7']) > 0:
            login_reward['7'] = login_reward['7'][0]
        else:
            login_reward['7'] = 1001

        for k, v in content.items():
            tmp = {'value': int(k), 'label': v['name'] + '--' + k}
            doc_card_list.append(tmp)
        result['login_reward'] = login_reward
        result['doc_card_list'] = doc_card_list
        result['selected_card_list'] = selected_card_list

    elif _type == 'update_login_reward':
        login_reward = update_data['data']
        selected_card_list = update_data['selected_card_list']
        hero_list =[]
        for node in selected_card_list:
            hero_list.append(node['value'])
        hero_list.sort()
        login_reward['7'] = hero_list
        project_data.login_reward = json.dumps(login_reward)
        db.session.commit()

    elif _type == 'consume_group':
        consume_group = json.loads(project_data.consume_group)
        for i in range(5):
            if str(i) not in consume_group:
                consume_group[str(i)] = []
            else:
                for ii in range(len(consume_group[str(i)])):
                    consume_group[str(i)][ii]['idx'] = ii

        task_score_list = {}
        with open(STATIC_PATH + 'huigui_consume_task_list.json', encoding='utf-8') as f:
            task_score_list = json.load(f)

        basic = json.loads(project_data.basic)

        result['consume_group']= consume_group
        result['task_score_list']= task_score_list

    elif _type == 'update_consume_group':
        data  = update_data['data']
        for k, v in data.items():
            for i in range(len(v)):
                node = v[i]
                if 'idx' in node:
                    del node['idx']

        project_data.consume_group = json.dumps(data)
        db.session.commit()

    elif _type == 'iap_group':
        iap_group = json.loads(project_data.iap_group)
        free_reward_refresh_time = 86400
        if 'free_reward_refresh_time' in iap_group:
            free_reward_refresh_time = iap_group['free_reward_refresh_time']
        free_reward = iap_group['free_reward'] if 'free_reward' in iap_group else []
        pay_reward = iap_group['pay_reward']
        pay_reward_line_list = []
        for i in range(len(pay_reward)):
            num = pay_reward[i]
            pay_reward_line = num // 1000
            pay_reward_sub_line = num % 1000
            pay_reward_line_list.append({'idx': i,
                              'pay_reward_line': pay_reward_line,
                              'pay_reward_sub_line': pay_reward_sub_line})

        line_list = []
        sub_line_list = {}
        with open(IAP_THEME_LINE_PATH + 'iap_theme_line.json.new', encoding='utf-8') as f:
            content = json.load(f)
        for k, v in content.items():
            line_tmp = {'value': int(k), 'label': '{0}--{1}'.format(k, v['name'])}
            line_list.append(line_tmp)
            sub_line_list[k] = []
            for sub_k, sub_v in v['line'].items():
                sub_line_tmp = {'value': int(sub_k),
                                'label': '{0}--{1}'.format(sub_k, sub_v['name'])}
                sub_line_list[k].append(sub_line_tmp)

        basic = json.loads(project_data.basic)

        result['free_reward'] = free_reward
        result['free_reward_refresh_time'] = free_reward_refresh_time
        # result['pay_reward_line'] = pay_reward_line
        # result['pay_reward_sub_line'] = pay_reward_sub_line
        result['line_list'] = line_list
        result['sub_line_list'] = sub_line_list
        result['pay_reward_line_list'] = pay_reward_line_list

    elif _type == 'update_iap_group':
        iap_group = update_data['data']
        pay_reward = iap_group['pay_reward_line_list']
        new_pay_reward = []
        for node in pay_reward:
            line = node['pay_reward_line']
            sub_line = node['pay_reward_sub_line']
            new_pay_reward.append(line*1000 + sub_line)
        new_iap_group = {
            'free_reward': iap_group['free_reward'],
            'pay_reward': new_pay_reward,
            'free_reward_refresh_time': iap_group['free_reward_refresh_time']}

        project_data.iap_group = json.dumps(new_iap_group)
        db.session.commit()

    elif _type == 'new_journey_iap_group':
        iap_group = json.loads(project_data.new_journey_iap_group)
        free_reward_refresh_time = 86400
        if 'free_reward_refresh_time' in iap_group:
            free_reward_refresh_time = iap_group['free_reward_refresh_time']
        free_reward = iap_group['free_reward'] if 'free_reward' in iap_group else []
        pay_reward = iap_group['pay_reward']
        pay_reward_line_list = []
        for i in range(len(pay_reward)):
            num = pay_reward[i]
            pay_reward_line = num // 1000
            pay_reward_sub_line = num % 1000
            pay_reward_line_list.append({'idx': i,
                              'pay_reward_line': pay_reward_line,
                              'pay_reward_sub_line': pay_reward_sub_line})

        line_list = []
        sub_line_list = {}
        with open(IAP_THEME_LINE_PATH + 'iap_theme_line.json.new', encoding='utf-8') as f:
            content = json.load(f)
        for k, v in content.items():
            line_tmp = {'value': int(k), 'label': '{0}--{1}'.format(k, v['name'])}
            line_list.append(line_tmp)
            sub_line_list[k] = []
            for sub_k, sub_v in v['line'].items():
                sub_line_tmp = {'value': int(sub_k),
                                'label': '{0}--{1}'.format(sub_k, sub_v['name'])}
                sub_line_list[k].append(sub_line_tmp)

        basic = json.loads(project_data.basic)

        result['free_reward'] = free_reward
        result['free_reward_refresh_time'] = free_reward_refresh_time
        # result['pay_reward_line'] = pay_reward_line
        # result['pay_reward_sub_line'] = pay_reward_sub_line
        result['line_list'] = line_list
        result['sub_line_list'] = sub_line_list
        result['pay_reward_line_list'] = pay_reward_line_list

    elif _type == 'update_new_journey_iap_group':
        iap_group = update_data['data']
        pay_reward = iap_group['pay_reward_line_list']
        new_pay_reward = []
        for node in pay_reward:
            line = node['pay_reward_line']
            sub_line = node['pay_reward_sub_line']
            new_pay_reward.append(line*1000 + sub_line)
        new_iap_group = {
            'free_reward': iap_group['free_reward'],
            'pay_reward': new_pay_reward,
            'free_reward_refresh_time': iap_group['free_reward_refresh_time']}

        project_data.new_journey_iap_group = json.dumps(new_iap_group)
        db.session.commit()

    elif _type == 'task_group':
        task_group = json.loads(project_data.task_group)
        task_tabs = []
        tabIndex = 0
        day_list = []
        for k, v in task_group.items():
            for i in range(len(v)):
                node = v[i]
                node['idx'] = i
            day_list.append(int(k))

        total_group = len(day_list)
        if len(day_list) > 0:
            tabIndex = max(day_list)
        day_list.sort()
        for i in day_list:
            task_tabs.append({'title': '第{}天'.format(i),
                              'name': str(i)})

        task_score_list = []
        with open(STATIC_PATH + 'huigui_task_score.json', encoding='utf-8') as f:
            task_score_list = json.load(f)

        basic = json.loads(project_data.basic)

        result['task_score_list']= task_score_list
        result['task_tabs']= task_tabs
        result['task_group']= task_group
        result['tabIndex']= tabIndex
        result['total_group']= total_group

    elif _type == 'update_task_group':
        task_group = update_data['data']
        day_list = []
        for k, v in task_group.items():
            for node in v:
                if 'idx' in node:
                    del node['idx']
                # 加入联盟的target默认值为1
                if node['task_type'] == 58:
                    node['target'] = 1
            day_list.append(int(k))
        new_task_group = {}
        day_list.sort()
        for i in range(len(day_list)):
            day = str(day_list[i])
            new_day = str(i+1)
            new_task_group[new_day] = task_group[day]

        project_data.task_group = json.dumps(new_task_group)
        db.session.commit()

    elif _type == 'score_reward':
        score_reward = json.loads(project_data.score_reward)
        for i in range(len(score_reward)):
            node = score_reward[i]
            node['idx'] = i
        result['score_reward'] = score_reward

    elif _type == 'update_score_reward':
        score_reward = update_data['data']
        for node in score_reward:
            if 'idx' in node:
                del node['idx']
        project_data.score_reward = json.dumps(score_reward)
        db.session.commit()

    elif _type == 'new_journey_task_group':
        task_group = json.loads(project_data.new_journey_task_group)
        task_tabs = []
        tabIndex = 0
        day_list = []
        for k, v in task_group.items():
            for i in range(len(v)):
                node = v[i]
                node['idx'] = i
            day_list.append(int(k))

        total_group = len(day_list)
        if len(day_list) > 0:
            tabIndex = max(day_list)
        day_list.sort()
        for i in day_list:
            task_tabs.append({'title': '第{}天'.format(i),
                              'name': str(i)})

        task_score_list = []
        with open(STATIC_PATH + 'huigui_task_score.json', encoding='utf-8') as f:
            task_score_list = json.load(f)

        basic = json.loads(project_data.basic)

        result['task_score_list']= task_score_list
        result['task_tabs']= task_tabs
        result['task_group']= task_group
        result['tabIndex']= tabIndex
        result['total_group']= total_group

    elif _type == 'update_new_journey_task_group':
        task_group = update_data['data']
        day_list = []
        for k, v in task_group.items():
            for node in v:
                if 'idx' in node:
                    del node['idx']
                # 加入联盟的target默认值为1
                if node['task_type'] == 58:
                    node['target'] = 1
            day_list.append(int(k))
        new_task_group = {}
        day_list.sort()
        for i in range(len(day_list)):
            day = str(day_list[i])
            new_day = str(i+1)
            new_task_group[new_day] = task_group[day]

        project_data.new_journey_task_group = json.dumps(new_task_group)
        db.session.commit()

    elif _type == 'new_journey_score_reward':
        score_reward = json.loads(project_data.new_journey_score_reward)
        for i in range(len(score_reward)):
            node = score_reward[i]
            node['idx'] = i
        result['score_reward'] = score_reward

    elif _type == 'update_new_journey_score_reward':
        score_reward = update_data['data']
        for node in score_reward:
            if 'idx' in node:
                del node['idx']
        project_data.new_journey_score_reward = json.dumps(score_reward)
        db.session.commit()

    elif _type == 'migration':
        basic = json.loads(project_data.basic)
        migration = {}
        if 'migration_svr_open_time' in basic:
            migration['migration_svr_open_time'] = basic['migration_svr_open_time']
        if 'migration_offline_day' in basic:
            migration['migration_offline_day'] = basic['migration_offline_day']
        migration['basic_offline_day'] = basic['offline_day']
        result['migration'] = migration

    elif _type == 'update_migration':
        migration = update_data['data']
        basic = json.loads(project_data.basic)
        basic['migration_svr_open_time'] = migration['migration_svr_open_time']
        basic['migration_offline_day'] = migration['migration_offline_day']

        project_data.basic = json.dumps(basic)
        db.session.commit()

    elif _type == 'get_doc_id_list':
        resp = get_doc_id_list_in_operation_event_english('return_event', 'title')
        return jsonify({
            'status': resp['status'],
            'doc_id_list': resp['doc_id_list']
        })

    return jsonify(result)


@app.route('/backflow_main_proj_new_action', methods=['POST'])
def backflow_main_proj_new_action():
    params = json.loads(request.data)
    result_data = {'status': 'success'}
    _type = params['type']
    _project = params['project']
    if _type == 'get_benefits_data':
        q = BackflowMainProj.query.filter_by(project=_project).first()
        result_data['data'] = json.loads(q.benefits)
    elif _type == 'get_new_journey_data':
        q = BackflowMainProj.query.filter_by(project=_project).first()
        result_data['data'] = json.loads(q.new_journey)
    elif _type == 'get_multiday_recharge_data':
        q = BackflowMainProj.query.filter_by(project=_project).first()
        result_data['data'] = json.loads(q.multiday_recharge)
    elif _type == 'get_new_journey_multiday_recharge_data':
        q = BackflowMainProj.query.filter_by(project=_project).first()
        result_data['data'] = json.loads(q.new_journey_multiday_recharge)
    elif _type == 'get_store_treasure_data':
        q = BackflowMainProj.query.filter_by(project=_project).first()
        result_data['data'] = json.loads(q.store_treasure)
    elif _type == 'get_new_journey_store_treasure_data':
        q = BackflowMainProj.query.filter_by(project=_project).first()
        result_data['data'] = json.loads(q.new_journey_store_treasure)
    elif _type == 'get_inheritance_data':
        q = BackflowMainProj.query.filter_by(project=_project).first()
        result_data['data'] = json.loads(q.inheritance)
    elif _type == 'update_part':
        _part = params['part']
        q = BackflowMainProj.query.filter_by(project=_project).first()
        if _part == 'benefits':
            q.benefits = json.dumps(params['data'])
        elif _part == 'new_journey':
            q.new_journey = json.dumps(params['data'])
        elif _part == 'multiday_recharge':
            q.multiday_recharge = json.dumps(params['data'])
        elif _part == 'new_journey_multiday_recharge':
            q.new_journey_multiday_recharge = json.dumps(params['data'])
        elif _part == 'store_treasure':
            q.store_treasure = json.dumps(params['data'])
        elif _part == 'new_journey_store_treasure':
            q.new_journey_store_treasure = json.dumps(params['data'])
        elif _part == 'inheritance':
            q.inheritance = json.dumps(params['data'])
        db.session.commit()
    elif _type == 'sub_event_clone':
        _part = params['part']
        _target = params['target']
        _event_type = params['event_type']
        if _part == 'new_login_reward':
            f = BackflowMainProj.query.filter_by(project=_project).first()
            t = BackflowMainProj.query.filter_by(project=_target).first()
            if f and t:
                if _event_type == 'old':
                    t.login_reward = f.login_reward
                elif _event_type == 'new':
                    t.new_journey_login_reward = f.login_reward
                elif _event_type == 'n-old':
                    t.login_reward = f.new_journey_login_reward
                elif _event_type == 'n-new':
                    t.new_journey_login_reward = f.new_journey_login_reward
        elif _part == 'task_group':
            f = BackflowMainProj.query.filter_by(project=_project).first()
            t = BackflowMainProj.query.filter_by(project=_target).first()
            if f and t:
                if _event_type == 'old':
                    t.task_group = f.task_group
                    t.score_reward = f.score_reward
                elif _event_type == 'new':
                    t.new_journey_task_group = f.task_group
                    t.new_journey_score_reward = f.score_reward
                elif _event_type == 'n-old':
                    t.task_group = f.new_journey_task_group
                    t.score_reward = f.new_journey_score_reward
                elif _event_type == 'n-new':
                    t.new_journey_task_group = f.new_journey_task_group
                    t.new_journey_score_reward = f.new_journey_score_reward
        elif _part == 'iap_group':
            f = BackflowMainProj.query.filter_by(project=_project).first()
            t = BackflowMainProj.query.filter_by(project=_target).first()
            if f and t:
                if _event_type == 'old':
                    t.iap_group = f.iap_group
                elif _event_type == 'new':
                    t.new_journey_iap_group = f.iap_group
                elif _event_type == 'n-old':
                    t.iap_group = f.new_journey_iap_group
                elif _event_type == 'n-new':
                    t.new_journey_iap_group = f.new_journey_iap_group
        elif _part == 'multiday_recharge':
            f = BackflowMainProj.query.filter_by(project=_project).first()
            t = BackflowMainProj.query.filter_by(project=_target).first()
            if f and t:
                if _event_type == 'old':
                    t.multiday_recharge = f.multiday_recharge
                elif _event_type == 'new':
                    t.new_journey_multiday_recharge = f.multiday_recharge
                elif _event_type == 'n-old':
                    t.multiday_recharge = f.new_journey_multiday_recharge
                elif _event_type == 'n-new':
                    t.new_journey_multiday_recharge = f.new_journey_multiday_recharge
        elif _part == 'store_treasure':
            f = BackflowMainProj.query.filter_by(project=_project).first()
            t = BackflowMainProj.query.filter_by(project=_target).first()
            if f and t:
                if _event_type == 'old':
                    t.store_treasure = f.store_treasure
                elif _event_type == 'new':
                    t.new_journey_store_treasure = f.store_treasure
                elif _event_type == 'n-old':
                    t.store_treasure = f.new_journey_store_treasure
                elif _event_type == 'n-new':
                    t.new_journey_store_treasure = f.new_journey_store_treasure
        elif _part == 'consume_group':
            f = BackflowMainProj.query.filter_by(project=_project).first()
            t = BackflowMainProj.query.filter_by(project=_target).first()
            if f and t:
                if _event_type == 'old':
                    t.consume_group = f.consume_group
        elif _part == 'migration':
            f = BackflowMainProj.query.filter_by(project=_project).first()
            t = BackflowMainProj.query.filter_by(project=_target).first()
            f_basic = json.loads(f.basic)
            t_basic = json.loads(t.basic)
            if f and t:
                if _event_type == 'old':
                    t_basic['migration_svr_open_time'] = f_basic['migration_svr_open_time']
                    t_basic['migration_offline_day'] = f_basic['migration_offline_day']
                    t.basic = json.dumps(t_basic)
        elif _part == 'new_journey':
            f = BackflowMainProj.query.filter_by(project=_project).first()
            t = BackflowMainProj.query.filter_by(project=_target).first()
            if f and t:
                if _event_type == 'old':
                    t.new_journey = f.new_journey
        elif _part == 'benefits':
            f = BackflowMainProj.query.filter_by(project=_project).first()
            t = BackflowMainProj.query.filter_by(project=_target).first()
            if f and t:
                if _event_type == 'n-new':
                    t.benefits = f.benefits
        elif _part == 'inheritance':
            f = BackflowMainProj.query.filter_by(project=_project).first()
            t = BackflowMainProj.query.filter_by(project=_target).first()
            if f and t:
                if _event_type == 'n-new':
                    t.inheritance = f.inheritance
        db.session.commit()
    elif _type == 'get_pid_list':
        query = BackflowMainProj.query.order_by('project').all()
        result = []
        for i in query:
            result.append({
                'value': i.project,
                'label': f"{i.project} - {i.remark}"
            })
        result_data['data'] = result
    elif _type == 'get_coupon_list':
        result = []
        with open(GLOBAL_PATH + 'sub_game.json', encoding='utf-8') as f:
            sub_game_data = json.load(f)
            for i in sub_game_data['sub_game_common_discount_coupon']:
                current_coupon = sub_game_data['sub_game_common_discount_coupon'][i]
                if current_coupon['coupon_type'] == 0:
                    result.append({
                        'id': int(i),
                        'label': f"{i} - {current_coupon['denomination']}",
                        'denomination': current_coupon['denomination']
                    })
        result_data['data'] = result
    return jsonify(result_data)


@app.route('/backflow_main_proj_down/<int:is_push>/<int:event_num>', methods=['GET', 'POST'])
def backflow_main_proj_down(is_push, event_num):
    main_result = {}
    login_result = {}
    task_result = {}
    consume_result = {}
    iap_result = {}
    migration_result = {}
    benefits_result = {}
    new_journey_result = {}
    multiday_recharge_result = {}
    store_treasure_result = {}
    inheritance_result = {}

    with open(STATIC_PATH + 'backflow_task_content.json', encoding='utf-8') as f:
        task_content = json.load(f)
    with open(STATIC_PATH + 'huigui_task_score.json', encoding='utf-8') as f:
        huigui_task_score = json.load(f)
    with open(GLOBAL_PATH + 'new_operation_event.json', encoding='utf-8') as f:
        new_operation_event_data = json.load(f)

    consume_cp_doc_id = {'65': 18, '50': 19, '57': 20, '66': 21, '67': 22}
    task_cp_doc_id = {'58': 1, '42': 2, '43': 6, '8004': 4, '8003': 3,
                      '49': 5, '59': 7, '60': 8, '61': 9, '22': 10, '33': 11,
                      '28': 12, '62': 13, '63': 14, '57': 15, '50': 16, '64': 17}

    event_ui = 1
    new_journey_event_ui = 2
    query = BackflowMainProj.query.all()
    for que in query:
        pid = str(que.project)

        # main_proj
        main_basic = json.loads(que.basic)
        offline_day = main_basic['offline_day'] * 86400
        # main_basic['offline_day'] *= 86400
        # main_basic['event_ui'] = event_ui

        sec = {
            'day': sec_1day,
            'hour': sec_1hour,
            'minute': sec_1min,
            'second': sec_1sec
        }[main_basic['cd_unit']]
        cd = main_basic['cd'] * sec
        main_result[pid] = {
            'basic': {
                'event_ui': event_ui,
                'offline_day': offline_day,
                'castle_lv': main_basic['castle_lv'],
                'cd': cd,
            },
            'localization': {
                'title': main_basic['doc_id']
            },
            'sub_event_open_control': main_basic['open_control'],
            '__remark': que.remark
        }
        main_result[str(int(pid) + 1000)] = {
            'basic': {
                'event_ui': new_journey_event_ui,
                'offline_day': offline_day,
                'castle_lv': main_basic['castle_lv'],
                'cd': cd,
            },
            'localization': {
                'title': main_basic['new_journey_doc_id']
            },
            'sub_event_open_control': main_basic['open_control'],
            '__remark': que.remark
        }

        # login_proj
        login_reward = json.loads(que.login_reward)
        # login_localization = json.loads(que.login_localization)
        # task_doc_localization = json.loads(que.task_doc_localization)
        # 20230427 from aurora
        task_doc_localization = {"consume": {"50": 493, "57": 494, "65": 492, "66": 495, "67": 496},
                                 "login": {"1": 467, "2": 468, "3": 469, "4": 470, "5": 471, "6": 472, "7": 473,
                                           "8": 474},
                                 "task": {"22": 484, "28": 486, "33": 485, "42": 476, "43": 480, "49": 479, "50": 490,
                                          "57": 489, "58": 475, "59": 481, "60": 482, "61": 483, "62": 487, "63": 488,
                                          "64": 491, "65": 492, "8003": 478, "8004": 477}}
        new_login_reward = []
        day_list = []
        for k in login_reward.keys():
            day_list.append(int(k))
        day_list.sort()
        for day in day_list:
            reward = login_reward[str(day)]
            if day != 7:
                reward = RewardToTMysqlNew(reward)
            else:
                reward_card = []
                for card_id in reward:
                    reward_card.append({'a': [84, card_id, 8]})
                reward = reward_card
            # login_reward 固定任务内容
            tmp = {'task_id': day+1, 'task_type': 71,
                   'target': day+1, 'reward': reward,
                   'detail': [0, 0, 2]}
            new_login_reward.append(tmp)

        login_localization = {
            'title': main_basic['doc_id'],
            'sub_title': main_basic['doc_id'],
            'info': main_basic['doc_id'],
            'task_doc': {}
        }
        for day in day_list:
            login_localization['task_doc'][str(day+1)] = task_doc_localization['login'][str(day+1)]
        if main_basic['open_control']['old']['login']:
            login_result[pid] = {
            'basic': {
                'event_ui': 501  # login_ui
            },
            'localization': login_localization,
            'login_reward': new_login_reward
        }

        ### new_journey_login_reward begin
        login_reward = json.loads(que.new_journey_login_reward)
        # task_doc_localization = json.loads(que.task_doc_localization)

        new_login_reward = []
        day_list = []
        for k in login_reward.keys():
            day_list.append(int(k))
        day_list.sort()
        for day in day_list:
            reward = login_reward[str(day)]
            if day != 7:
                reward = RewardToTMysqlNew(reward)
            else:
                reward_card = []
                for card_id in reward:
                    reward_card.append({'a': [84, card_id, 8]})
                reward = reward_card
            # login_reward 固定任务内容
            tmp = {'task_id': day + 1, 'task_type': 71,
                   'target': day + 1, 'reward': reward,
                   'detail': [0, 0, 2]}
            new_login_reward.append(tmp)

        login_localization = {
            'title': main_basic['doc_id'],
            'sub_title': main_basic['doc_id'],
            'info': main_basic['doc_id'],
            'task_doc': {}
        }
        for day in day_list:
            login_localization['task_doc'][str(day + 1)] = task_doc_localization['login'][str(day + 1)]
        if main_basic['open_control']['new']['login']:
            login_result[str(int(pid) + 1000)] = {
            'basic': {
                'event_ui': 501  # login_ui
            },
            'localization': login_localization,
            'login_reward': new_login_reward
        }
        ### new_journey_login_reward end

        # consume_proj
        consume_group = json.loads(que.consume_group)
        # consume_localization = json.loads(que.consume_localization)
        # task_doc_localization = json.loads(que.task_doc_localization)
        new_consume_group = []
        consume_list = []
        consume_doc_list = [] # task_id, task_type

        for k in consume_group.keys():
            consume_list.append(int(k))
        consume_list.sort()
        for i in consume_list:
            cur_consume_group = []
            cur_list = consume_group[str(i)]
            for ii in range(len(cur_list)):
                node = cur_list[ii]
                node['reward'] = RewardToTMysqlNew(node['reward'])
                type_node = task_content[str(node['type'])]
                detail_id = type_node['detail_id']
                detail_level = type_node['detail_level']
                op_type = type_node['op_type']
                if type_node['time_flag']:
                    target = node['target'] * 60
                    target_unit = 60
                else:
                    target = node['target']
                    target_unit = 1
                task_id = (i+1)*1000 + ii
                cur_consume_group.append(
                    {'task_id': task_id, 'target': target,
                     'task_type': node['type'],
                     'target_unit': target_unit,
                     'detail': [detail_id, detail_level, op_type],
                     'reward': node['reward']})
                consume_doc_list.append((task_id, node['type']))
            new_consume_group.append(cur_consume_group)

        consume_localization = {
            'title': main_basic['doc_id'],
            'info': main_basic['doc_id'],
            'task_doc': {},
            # from bliss
            'group_title': [
                {
                    'title': 1,
                    'info': 1
                },
                {
                    'title': 2,
                    'info': 2
                },
                {
                    'title': 3,
                    'info': 3
                },
                {
                    'title': 4,
                    'info': 4
                },
                {
                    'title': 5,
                    'info': 5
                }
            ]
        }

        for array in consume_doc_list:
            task_id = str(array[0])
            consume_localization['task_doc'][task_id] = task_doc_localization['consume'][str(array[1])]

        if main_basic['open_control']['old']['consume']:
            consume_result[pid] = {'basic': {'event_ui': 503},  # consume_ui
                               'localization': consume_localization,
                               'consume_group': new_consume_group}

        # task_proj
        task_group = json.loads(que.task_group)
        score_reward = json.loads(que.score_reward)
        # task_localization = json.loads(que.task_localization)
        day_doc_localization = json.loads(que.day_doc_localization)
        # task_doc_localization = json.loads(que.task_doc_localization)

        new_task_group = []
        task_list = []
        task_doc_list = []
        for i in range(len(score_reward)):
            node = score_reward[i]
            node['task_id'] = 1000 + i
            node['reward'] = RewardToTMysqlNew(node['reward'])
        for k in task_group.keys():
            task_list.append(int(k))
        task_list.sort()

        day_nums = len(task_list)

        for i in task_list:
            cur_task_group = []
            cur_list = task_group[str(i)]
            for ii in range(len(cur_list)):
                node = cur_list[ii]
                node['reward'] = RewardToTMysqlNew(node['reward'])
                task_id = i*10000 + ii
                task_type = node['task_type']
                # 宝箱任务特殊处理
                if task_type == 8004 or task_type == 8003:
                    detail_id = task_type - 8000
                    task_type = 8
                else:
                    detail_id = task_content[str(task_type)]['detail_id']
                detail_level = task_content[str(task_type)]['detail_level']
                op_type = task_content[str(task_type)]['op_type']
                target = node['target']
                if task_content[str(task_type)]['time_flag']:
                    target_unit = 60
                    target *= 60
                else:
                    target_unit = 1
                if task_content[str(task_type)]['level_flag']:
                    detail_id = target
                cur_task_group.append(
                    {'task_id': task_id, 'task_type': task_type,
                     'target': target, 'target_unit': target_unit,
                     'detail': [detail_id, detail_level, op_type],
                     'reward': node['reward'],
                     'score': node['score']})
                # 宝箱任务特殊处理
                if task_type == 8:
                    task_type = task_type*1000 + detail_id
                task_doc_list.append((task_id, task_type))
            new_task_group.append(cur_task_group)

        task_localization = {
            'title': main_basic['doc_id'],
            'info': main_basic['doc_id'],
            'task_doc': {},
            'day_doc': []
        }
        for array in task_doc_list:
            task_id = str(array[0])
            task_type = str(array[1])
            task_localization['task_doc'][task_id] = task_doc_localization['task'][task_type]


        for i in range(day_nums):
            task_localization['day_doc'].append(task_doc_localization['login'][str(i + 1)])
        if main_basic['open_control']['old']['back_task']:
            task_result[pid] = {
            'basic': {
                'event_ui': 502  # task_ui
            },
            'localization': task_localization,
            'task_group': new_task_group,
            'score_reward': score_reward
        }

        ### new_journey_task begin
        task_group = json.loads(que.new_journey_task_group)
        score_reward = json.loads(que.new_journey_score_reward)
        # task_localization = json.loads(que.task_localization)
        day_doc_localization = json.loads(que.day_doc_localization)
        # task_doc_localization = json.loads(que.task_doc_localization)

        new_task_group = []
        task_list = []
        task_doc_list = []
        for i in range(len(score_reward)):
            node = score_reward[i]
            node['task_id'] = 1000 + i
            node['reward'] = RewardToTMysqlNew(node['reward'])
        for k in task_group.keys():
            task_list.append(int(k))
        task_list.sort()

        day_nums = len(task_list)

        for i in task_list:
            cur_task_group = []
            cur_list = task_group[str(i)]
            for ii in range(len(cur_list)):
                node = cur_list[ii]
                node['reward'] = RewardToTMysqlNew(node['reward'])
                task_id = i * 10000 + ii
                task_type = node['task_type']
                # 宝箱任务特殊处理
                if task_type == 8004 or task_type == 8003:
                    detail_id = task_type - 8000
                    task_type = 8
                else:
                    detail_id = task_content[str(task_type)]['detail_id']
                detail_level = task_content[str(task_type)]['detail_level']
                op_type = task_content[str(task_type)]['op_type']
                target = node['target']
                if task_content[str(task_type)]['time_flag']:
                    target_unit = 60
                    target *= 60
                else:
                    target_unit = 1
                if task_content[str(task_type)]['level_flag']:
                    detail_id = target
                cur_task_group.append(
                    {'task_id': task_id, 'task_type': task_type,
                     'target': target, 'target_unit': target_unit,
                     'detail': [detail_id, detail_level, op_type],
                     'reward': node['reward'],
                     'score': node['score']})
                # 宝箱任务特殊处理
                if task_type == 8:
                    task_type = task_type * 1000 + detail_id
                task_doc_list.append((task_id, task_type))
            new_task_group.append(cur_task_group)

        task_localization = {
            'title': main_basic['doc_id'],
            'info': main_basic['doc_id'],
            'task_doc': {},
            'day_doc': []
        }
        for array in task_doc_list:
            task_id = str(array[0])
            task_type = str(array[1])
            task_localization['task_doc'][task_id] = task_doc_localization['task'][task_type]

        for i in range(day_nums):
            task_localization['day_doc'].append(task_doc_localization['login'][str(i + 1)])
        if main_basic['open_control']['new']['back_task']:
            task_result[str(int(pid) + 1000)] = {
            'basic': {
                'event_ui': 502  # task_ui
            },
            'localization': task_localization,
            'task_group': new_task_group,
            'score_reward': score_reward
        }
        ### new_journey_task end

        # iap_proj
        iap_group = json.loads(que.iap_group)
        # iap_localization = json.loads(que.iap_localization)
        free_reward = RewardToTMysqlNew(iap_group['free_reward'])
        if main_basic['open_control']['old']['back_iap']:
            iap_result[pid] = {
            'basic': {
                'event_ui': 504  # iap_ui
            },
            # 'localization': iap_localization,
            'localization': {
                'title': main_basic['doc_id'],
                'info': main_basic['doc_id']
            },
            'free_reward': free_reward,
            'free_reward_refresh_time': iap_group['free_reward_refresh_time'],
            'pay_reward': iap_group['pay_reward']
        }

        ### new_journey_iap begin
        iap_group = json.loads(que.new_journey_iap_group)
        free_reward = RewardToTMysqlNew(iap_group['free_reward'])
        if main_basic['open_control']['new']['back_iap']:
            iap_result[str(int(pid) + 1000)] = {
            'basic': {
                'event_ui': 504  # iap_ui
            },
            # 'localization': iap_localization,
            'localization': {
                'title': main_basic['doc_id'],
                'info': main_basic['doc_id']
            },
            'free_reward': free_reward,
            'free_reward_refresh_time': iap_group['free_reward_refresh_time'],
            'pay_reward': iap_group['pay_reward']
        }
        ### new_journey_iap end

        # migration_proj
        migration_localization = json.loads(que.migration_localization)
        if main_basic['open_control']['old']['migration']:
            migration_result[pid] = {
            'basic': {
                'event_ui': 505,  # migration_ui
                'svr_open_time': main_basic['migration_svr_open_time'] * sec_1day,
                'offline_day': main_basic['migration_offline_day'] * sec_1day
            },
            'localization': {
                'title': main_basic['doc_id'],
                'sub_title': main_basic['doc_id'],
                'info': main_basic['doc_id']
            }
        }

        benefits = json.loads(que.benefits)
        benefitsBuff = []
        for i in benefits['buff']:
            benefitsBuff.append([i['id'], i['num'], i['time']])
        if main_basic['open_control']['new']['benefits']:
            benefits_result[str(int(pid) + 1000)] = {
            'basic': {
                'event_ui': 63  # benefits
            },
            'localization': {
                'title': main_basic['doc_id'],
                'sub_title': main_basic['doc_id'],
                'info': main_basic['doc_id']
            },
            'reward': RewardToTMysqlNew(benefits['reward']),
            'buff': benefitsBuff
        }

        multiday_recharge = json.loads(que.multiday_recharge)
        multiday_recharge_target = []
        multiday_recharge_localization = {}
        for i in range(0, 21):
            current_localization = ''
            if 'multiday_charge_event' in new_operation_event_data:
                if str(multiday_recharge['doc_id']) in new_operation_event_data['multiday_charge_event']:
                    if str(i) in new_operation_event_data['multiday_charge_event'][str(multiday_recharge['doc_id'])]:
                        current_localization = new_operation_event_data['multiday_charge_event'][str(multiday_recharge['doc_id'])][str(i)]['title']
            multiday_recharge_localization[str(i + 1)] = {
                'title': current_localization
            }
        for i in multiday_recharge['target']:
            multiday_recharge_target.append({
                'score': i['score'],
                'reward': RewardToTMysqlNew(i['reward'])
            })
        if main_basic['open_control']['old']['multiday_recharge']:
            multiday_recharge_result[pid] = {
                'basic': {
                    'event_ui': 60  # multiday_recharge_ui
                },
                'localization': multiday_recharge_localization,
                'localization_doc': {
                    'title': multiday_recharge['doc_id']
                },
                'target': multiday_recharge_target
            }

        ### new_journey_multiday_recharge begin
        multiday_recharge = json.loads(que.new_journey_multiday_recharge)
        multiday_recharge_target = []
        multiday_recharge_localization = {}
        for i in range(0, 21):
            current_localization = ''
            if 'multiday_charge_event' in new_operation_event_data:
                if str(multiday_recharge['doc_id']) in new_operation_event_data['multiday_charge_event']:
                    if str(i) in new_operation_event_data['multiday_charge_event'][str(multiday_recharge['doc_id'])]:
                        current_localization = \
                        new_operation_event_data['multiday_charge_event'][str(multiday_recharge['doc_id'])][str(i)][
                            'title']
            multiday_recharge_localization[str(i + 1)] = {
                'title': current_localization
            }
        for i in multiday_recharge['target']:
            multiday_recharge_target.append({
                'score': i['score'],
                'reward': RewardToTMysqlNew(i['reward'])
            })
        if main_basic['open_control']['new']['multiday_recharge']:
            multiday_recharge_result[str(int(pid) + 1000)] = {
            'basic': {
                'event_ui': 60  # multiday_recharge_ui
            },
            'localization': multiday_recharge_localization,
            'localization_doc': {
                'title': multiday_recharge['doc_id']
            },
            'target': multiday_recharge_target
        }
        ### new_journey_multiday_recharge end

        store_treasure = json.loads(que.store_treasure)
        store_treasure_task_doc = {}
        store_treasure_task_group = []
        for i in store_treasure['reward']['list']:
            store_treasure_task_doc[str(i['task_id'])] = store_treasure['basic']['task_doc_id']
            store_treasure_task_group.append({
                'task_id': i['task_id'],
                'task_type': 78,
                'target': i['target'],
                'task_unit': 1,
                'detail': [0, 0, 2],
                'reward': RewardToTMysqlNew(i['reward']),
                'target_unit': 1
            })
        if main_basic['open_control']['old']['store_treasure']:
            store_treasure_result[pid] = {
            'basic': {
                'event_ui': 61,  # store_treasure_ui
                'tab_ui': store_treasure['basic']['tab_ui'],
                'score_id': store_treasure['basic']['score_id'],
                'u_score': store_treasure['basic']['u_score'],
                'iap_pid_list': ToSidList(store_treasure['basic']['iap_pid_list'])
            },
            'localization': {
                'title': store_treasure['doc_id'],
                'event_title': store_treasure['doc_id'],
                'info': store_treasure['doc_id'],
                'task_doc': store_treasure_task_doc
            },
            'task_group': [
                store_treasure_task_group
            ]
        }

        ### new_journey_store_treasure begin
        store_treasure = json.loads(que.new_journey_store_treasure)
        store_treasure_task_doc = {}
        store_treasure_task_group = []
        for i in store_treasure['reward']['list']:
            store_treasure_task_doc[str(i['task_id'])] = store_treasure['basic']['task_doc_id']
            store_treasure_task_group.append({
                'task_id': i['task_id'],
                'task_type': 78,
                'target': i['target'],
                'task_unit': 1,
                'detail': [0, 0, 2],
                'reward': RewardToTMysqlNew(i['reward']),
                'target_unit': 1
            })
        if main_basic['open_control']['new']['store_treasure']:
            store_treasure_result[str(int(pid) + 1000)] = {
            'basic': {
                'event_ui': 61,  # store_treasure_ui
                'tab_ui': store_treasure['basic']['tab_ui'],
                'score_id': store_treasure['basic']['score_id'],
                'u_score': store_treasure['basic']['u_score'],
                'iap_pid_list': ToSidList(store_treasure['basic']['iap_pid_list'])
            },
            'localization': {
                'title': store_treasure['doc_id'],
                'event_title': store_treasure['doc_id'],
                'info': store_treasure['doc_id'],
                'task_doc': store_treasure_task_doc
            },
            'task_group': [
                store_treasure_task_group
            ]
        }
        ### new_journey_store_treasure end

        inheritance = json.loads(que.inheritance)
        inheritance_reward_section = []
        for i in inheritance['reward_section']:
            _section = ToSidList(i['section'])
            _rate = ToSidList(i['rate'])
            for j in range(len(_rate)):
                _rate[j] *= 100
            inheritance_reward_section.append({
                'section': [_section[0], _section[1] + 1],
                'rate': _rate
            })
        if main_basic['open_control']['new']['inheritance']:
            inheritance_result[str(int(pid) + 1000)] = {
                'basic': {
                    'event_ui': 64,  # inheritance_ui
                    'old_pay_need': inheritance['basic']['old_pay_need']
                },
                'localization': {
                    'title': main_basic['doc_id'],
                    'sub_title': main_basic['doc_id'],
                    'info': main_basic['doc_id']
                },
                'inheritance': {
                    'old_pay_limit': inheritance['basic']['old_pay_limit'],
                    'rate': inheritance['basic']['rate'] * 100,
                    'evip_points': inheritance['basic']['evip_points'],
                    'coupon_rate': inheritance['basic']['coupon_rate'] * 100,
                    'point_rate': inheritance['basic']['point_rate'] * 100,
                    'coupon_list': ToSidList(inheritance['basic']['coupon_list']),
                    'reward_section': inheritance_reward_section
                }
            }

        new_journey = json.loads(que.new_journey)
        if main_basic['open_control']['old']['new_journey']:
            if main_basic['open_control']['new']['benefits']:
                benefits_reward = RewardToTMysqlNew(benefits['reward'])
                benefits_buff = benefitsBuff
            else:
                benefits_reward = []
                benefits_buff = []
            if main_basic['open_control']['new']['inheritance']:
                inheritance_rate = inheritance['basic']['rate'] * 100
            else:
                inheritance_rate = 0

            sec = {
                'day': sec_1day,
                'hour': sec_1hour,
                'minute': sec_1min,
                'second': sec_1sec
            }[new_journey['cd_unit']]
            cd = new_journey['cd'] * sec

            new_journey_result[pid] = {
                'basic': {
                    'event_ui': 62,  # new_journey_ui
                    'svr_open_time': new_journey['svr_open_time'] * sec_1day,
                    'offline_day': new_journey['offline_day'] * sec_1day,
                    'cd': cd,
                    'recommend_sid_num': new_journey['recommend_sid_num']
                },
                'localization': {
                    'title': main_basic['doc_id'],
                    'sub_title': main_basic['doc_id'],
                    'info': main_basic['doc_id']
                },
                'inheritance': {
                    'old_pay_need': inheritance['basic']['old_pay_need'],
                    'old_pay_limit': inheritance['basic']['old_pay_limit'],
                    'rate': inheritance_rate,
                    'evip_points': inheritance['basic']['evip_points'],
                    'coupon_rate': inheritance['basic']['coupon_rate'] * 100,
                    'point_rate': inheritance['basic']['point_rate'] * 100,
                    'coupon_list': ToSidList(inheritance['basic']['coupon_list']),
                    'reward_section': inheritance_reward_section
                },
                'benefits': {
                    'reward': benefits_reward,
                    'buff': benefits_buff
                }
            }


    if is_push ==0:
        if event_num == 0:
            response = DownLoad('backflow_main_proj', main_result, is_push)
        elif event_num == 1:
            response = DownLoad('backflow_login_proj', login_result, is_push)
        elif event_num == 2:
            response = DownLoad('backflow_consume_proj', consume_result, is_push)
        elif event_num == 3:
            response = DownLoad('backflow_task_proj', task_result, is_push)
        elif event_num == 4:
            response = DownLoad('backflow_iap_proj', iap_result, is_push)
        elif event_num == 5:
            response = DownLoad('backflow_migration_proj', migration_result, is_push)
        elif event_num == 6:
            response = DownLoad('backflow_benefits_proj', benefits_result, is_push)
        elif event_num == 7:
            response = DownLoad('backflow_new_journey_proj', new_journey_result, is_push)
        elif event_num == 8:
            response = DownLoad('multiday_recharge_proj.backflow', multiday_recharge_result, is_push)
        elif event_num == 9:
            response = DownLoad('store_treasure_proj.backflow', store_treasure_result, is_push)
        elif event_num == 10:
            response = DownLoad('backflow_inheritance_proj', inheritance_result, is_push)
    elif is_push == 1:
        response = DownLoad('backflow_main_proj', main_result, is_push)
        response = DownLoad('backflow_login_proj', login_result, is_push)
        response = DownLoad('backflow_consume_proj', consume_result, is_push)
        response = DownLoad('backflow_task_proj', task_result, is_push)
        response = DownLoad('backflow_iap_proj', iap_result, is_push)
        response = DownLoad('backflow_migration_proj', migration_result, is_push)
        response = DownLoad('backflow_benefits_proj', benefits_result, is_push)
        response = DownLoad('backflow_new_journey_proj', new_journey_result, is_push)
        response = DownLoad('multiday_recharge_proj.backflow', multiday_recharge_result, is_push)
        response = DownLoad('store_treasure_proj.backflow', store_treasure_result, is_push)
        response = DownLoad('backflow_inheritance_proj', inheritance_result, is_push)
    return response


@app.route('/get_pay_level_list', methods=['GET'])
def get_pay_level_list():
    result = {'msg': '成功','ret':0}
    data = []
    with open(IAP_THEME_LINE_PATH + 'pay_level.json.new', encoding='utf-8') as f:
        content = json.load(f)
    for k, v in content.items():
        tmp = {'value': k, 'label': '{0}--{1}'.format(k, v['name'])}
        data.append(tmp)
    result['data'] = data
    return jsonify(result)

@app.route('/event_type_mail_send', methods=['GET'])
def event_type_mail_send():
    data = EventTypeMailSend.query.first()
    result= {}
    data_list = []
    iron_doc_ids = []
    super_doc_ids = []
    svs_doc_ids = []
    western_shadow_doc_ids = []
    conquest_match_doc_ids = []

    iron_throne = json.loads(data.iron_throne)
    super_throne = json.loads(data.super_throne)
    svs = json.loads(data.svs)
    other = json.loads(data.other)
    # 20220622 加入厄运暗影活动
    western_shadow = other['western_shadow_menu']
    conquest_match = other['conquest_match']  # 20230130 征服者雄心联赛

    iron_throne['name'] = 'iron_throne'
    super_throne['name'] = 'super_throne'
    svs['name'] = 'svs'
    western_shadow['name'] = 'bronze_throne'
    conquest_match['name'] = 'conquest_match'

    for node in [iron_throne, super_throne, svs, western_shadow, conquest_match]:
        data_list.append(node)

    with open(GLOBAL_PATH + 'document_english.json', encoding='utf-8') as f:
        content = json.load(f)
    doc_mails = content['doc_mail']
    for doc_id, doc_node in doc_mails.items():
        if doc_id == '1112':
            title = doc_node['title'] if doc_node['title'] else '无标题'
            svs_doc_ids.append({'value': int(doc_id), 'label': doc_id + '--' + title})
        elif doc_id == '1113':
            title = doc_node['title'] if doc_node['title'] else '无标题'
            svs_doc_ids.append({'value': int(doc_id), 'label': doc_id + '--' + title})
            super_doc_ids.append({'value': int(doc_id), 'label': doc_id + '--' + title})
            western_shadow_doc_ids.append({'value': int(doc_id), 'label': doc_id + '--' + title})
        elif int(doc_id) >= 1114:
            title = doc_node['title'] if doc_node['title'] else '无标题'
            svs_doc_ids.append({'value': int(doc_id), 'label': doc_id + '--' + title})
            super_doc_ids.append({'value': int(doc_id), 'label': doc_id + '--' + title})
            iron_doc_ids.append({'value': int(doc_id), 'label': doc_id + '--' + title})
            western_shadow_doc_ids.append({'value': int(doc_id), 'label': doc_id + '--' + title})
            conquest_match_doc_ids.append({'value': int(doc_id), 'label': doc_id + '--' + title})

    result['data_list'] = data_list
    result['svs_doc_ids'] = svs_doc_ids
    result['super_doc_ids'] = super_doc_ids
    result['iron_doc_ids'] = iron_doc_ids
    result['western_shadow_doc_ids'] = western_shadow_doc_ids
    result['conquest_match_doc_ids'] = conquest_match_doc_ids

    return jsonify(result)

@app.route('/event_type_mail_send_action', methods=['GET', 'POST'])
def event_type_mail_send_action():
    update_data = json.loads(request.data)
    result = {'msg': '成功', 'ret': 0}
    _type = update_data['type']
    project_data = EventTypeMailSend.query.first()
    # event_name_list = ['iron_throne', 'super_throne', 'svs']

    if _type == 'update':
        data_list = update_data['data_list']
        iron_throne = data_list[0]
        super_throne = data_list[1]
        svs = data_list[2]
        # 20220622 新加的都加入other中
        western_shadow_menu = data_list[3]
        conquest_match = data_list[4]

        other = json.loads(project_data.other)
        other['western_shadow_menu'] = western_shadow_menu
        other['conquest_match'] = conquest_match

        project_data.iron_throne = json.dumps(iron_throne)
        project_data.super_throne = json.dumps(super_throne)
        project_data.svs = json.dumps(svs)
        project_data.other = json.dumps(other)
        db.session.commit()

    return jsonify(result)

@app.route('/event_type_mail_send_down/<int:is_push>', methods= ['GET', 'POST'])
def event_type_mail_send_down(is_push):
    result_data = {}
    query = EventTypeMailSend.query.first()
    iron_throne = json.loads(query.iron_throne)
    super_throne = json.loads(query.super_throne)
    svs = json.loads(query.svs)
    # 20220622 新活动都加入到other中
    other = json.loads(query.other)
    western_shadow_menu = other['western_shadow_menu']
    conquest_match = other['conquest_match']

    for node in [iron_throne, super_throne, svs, western_shadow_menu, conquest_match]:
        cur_reward = RewardToTMysqlNew(node['reward'])
        cur_name = node['name']
        tmp = {'mail_conf':{
                'doc_id': node['doc_id'],
                'reward': cur_reward,
                'show_type': node['show_type'],
                'jump_type': node['jump_type']
                },
               'time_offset': node['time_offset']}
        result_data[cur_name] = tmp
    result_data['active_type'] = ['iron_throne', 'super_throne', 'svs', 'bronze_throne', 'conquest_match']

    response = DownLoad('event_type_mail_send', result_data, is_push)
    return response


@app.route('/recharge_rebate_project', methods=['GET'])
def recharge_rebate_project():
    query = RechargeRebateProject.query.order_by('project').all()
    result = []
    for que in query:
        loc = json.loads(que.localization)
        title = loc['1']['title'] if '1' in loc else ''
        tmp = {'project': que.project, 'title': title,
               'remark': que.remark}
        result.append(tmp)
    return jsonify(result)

@app.route('/recharge_rebate_project_action', methods=['GET', 'POST'])
def recharge_rebate_project_action():
    update_data = json.loads(request.data)
    result = {'msg': '成功','ret':0}
    _type = update_data['type']
    project = update_data['project']
    project_data = RechargeRebateProject.query.filter_by(project=project).first()

    if _type == 'remark':
        project_data.remark = update_data['remark']
        db.session.commit()

    elif _type == 'clone':
        new_project_data = RechargeRebateProject(
            basic=project_data.basic,
            localization=project_data.localization,
            task_list=project_data.task_list,
            remark=project_data.remark)
        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if (new_project_id is None):
            result = {'msg': '克隆失败','ret':2}
        else:
            result = {'msg': '克隆成功','ret':0}

    elif _type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = RechargeRebateProject.query.filter_by(project=project).first()
        if (new_project_data is None):
            result = {'msg': '删除成功','ret':0}
        else:
            result = {'msg': '删除失败','ret':1}

    elif _type == 'basic':
        basic = json.loads(project_data.basic)
        result['basic_data'] = basic

    elif _type == 'update_basic':
        basic = update_data['basic_data']
        project_data.basic = json.dumps(basic)
        db.session.commit()

    elif _type == 'task_list':
        task_list = json.loads(project_data.task_list)
        for i in range(len(task_list)):
            node = task_list[i]
            node['index'] = i
        result['data_list'] = task_list

    elif _type == 'update_task_list':
        task_list = update_data['data_list']
        max_task_id = 0
        for node in task_list:
            if 'index' in node:
                del node['index']
            if 'task_id' in node:
                max_task_id = max(max_task_id, node['task_id'])
        for node in task_list:
            if 'task_id' not in node or node['task_id'] == -1:
                node['task_id'] = max_task_id + 1
                max_task_id += 1
        project_data.task_list = json.dumps(task_list)
        db.session.commit()

    return jsonify(result)

@app.route('/recharge_rebate_project_down/<int:is_push>', methods=['GET', 'POST'])
def recharge_rebate_project_down(is_push):
    result_data = {}
    query = RechargeRebateProject.query.all()
    for que in query:
        pid = str(que.project)
        basic = json.loads(que.basic)
        localization = json.loads(que.localization)
        task_list = json.loads(que.task_list)
        remark = que.remark
        for i in range(len(task_list)):
            node = task_list[i]
            if 'index' in node:
                del node['index']
            node['reward'] = RewardToTMysqlNew(node['reward'])
            # node['task_id'] = i

            # target = node['gems']
            # for lang_id in range(1, 22):
            #     if 'STRING0' in localization[str(lang_id)]['task_info'][str(i)]:
            #         localization[str(lang_id)]['task_info'][str(i)] = localization[str(lang_id)]['task_info'][str(i)].replace('STRING0', str(target))

        result_data[pid] = {'basic': {'event_ui': basic['event_ui']},
                            'localization': localization,
                            'castle_lv': basic['castle_lv'],
                            'task_num': basic['task_num'],
                            'task': task_list,
                            'remark': remark}

    response = DownLoad('recharge_rebate_project', result_data, is_push)
    return response


@app.route('/novice_recharge_rebate_project', methods=['GET'])
def novice_recharge_rebate_project():
    query = NoviceRechargeRebateProject.query.order_by('project').all()
    result = []
    for que in query:
        loc = json.loads(que.localization)
        title = loc['1']['title'] if '1' in loc else ''
        tmp = {'project': que.project, 'title': title,
               'remark': que.remark}
        result.append(tmp)
    return jsonify(result)

@app.route('/novice_recharge_rebate_project_action', methods=['GET', 'POST'])
def novice_recharge_rebate_project_action():
    update_data = json.loads(request.data)
    result = {'msg': '成功','ret':0}
    _type = update_data['type']
    project = update_data['project']
    project_data = NoviceRechargeRebateProject.query.filter_by(project=project).first()

    if _type == 'remark':
        project_data.remark = update_data['remark']
        db.session.commit()

    elif _type == 'clone':
        new_project_data = NoviceRechargeRebateProject(
            basic=project_data.basic,
            localization=project_data.localization,
            task_list=project_data.task_list,
            remark=project_data.remark)
        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if (new_project_id is None):
            result = {'msg': '克隆失败','ret':2}
        else:
            result = {'msg': '克隆成功','ret':0}

    elif _type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = NoviceRechargeRebateProject.query.filter_by(project=project).first()
        if (new_project_data is None):
            result = {'msg': '删除成功','ret':0}
        else:
            result = {'msg': '删除失败','ret':1}

    elif _type == 'basic':
        basic = json.loads(project_data.basic)
        result['basic_data'] = basic

    elif _type == 'update_basic':
        basic = update_data['basic_data']
        project_data.basic = json.dumps(basic)
        db.session.commit()

    elif _type == 'task_list':
        task_list = json.loads(project_data.task_list)
        for i in range(len(task_list)):
            node = task_list[i]
            node['index'] = i
            node['pay_left'] = node['need_max_gems'][0]
            node['pay_right'] = node['need_max_gems'][1]
            del node['need_max_gems']
        result['data_list'] = task_list

    elif _type == 'update_task_list':
        task_list = update_data['data_list']
        max_task_id = 0
        for node in task_list:
            node['need_max_gems'] = [node['pay_left'], node['pay_right']]
            del node['pay_left']
            del node['pay_right']
            if 'index' in node:
                del node['index']
            if 'task_id' in node:
                max_task_id = max(max_task_id, node['task_id'])
        for node in task_list:
            if 'task_id' not in node or node['task_id'] == -1:
                node['task_id'] = max_task_id + 1
                max_task_id += 1
        project_data.task_list = json.dumps(task_list)
        db.session.commit()

    return jsonify(result)

@app.route('/novice_recharge_rebate_project_down/<int:is_push>', methods= ['GET', 'POST'])
def novice_recharge_rebate_project_down(is_push):
    result_data = {}
    query = NoviceRechargeRebateProject.query.all()
    for que in query:
        pid = str(que.project)
        basic = json.loads(que.basic)
        localization = json.loads(que.localization)
        task_list = json.loads(que.task_list)
        remark = que.remark

        for i in range(len(task_list)):
            node = task_list[i]
            node['reward'] = RewardToTMysqlNew(node['reward'])
            # node['task_id'] = i

            # target = node['gems']
            # for lang_id in range(1, 22):
            #     if 'STRING0' in localization[str(lang_id)]['task_info'][str(i)]:
            #         localization[str(lang_id)]['task_info'][str(i)] = localization[str(lang_id)]['task_info'][str(i)].replace('STRING0', str(target))

        result_data[pid] = {'basic': {'event_ui': basic['event_ui']},
                            'localization': localization,
                            'castle_lv': basic['castle_lv'],
                            'task': task_list,
                            'remark': remark}

    response = DownLoad('novice_recharge_rebate_project', result_data, is_push)
    return response


@app.route('/continuous_activities_proj', methods=['GET'])
def continuous_activities_proj():
    query = ContinuousActivitiesProj.query.order_by('project').all()
    result = []
    for que in query:
        project = int(que.project)
        localization = json.loads(que.localization)
        remark = que.remark
        if '1' in localization:
            title = localization['1']['title']
        else:
            title = ''
        tmp = {"project": project, "title": title, 'remark': remark}
        result.append(tmp)
    return jsonify(result)

@app.route('/get_continuous_activities_task_content', methods=['GET'])
def get_continuous_activities_task_content():
    result = {}
    task_label_list = []
    with open(STATIC_PATH + 'continuous_activities_task_content.json',
              encoding='utf-8') as f:
        content = json.load(f)
    task_content = content['task_type']
    detail_content = content['detail_type']
    task_cp_detail_list = {}

    for k, v in task_content.items():
        tmp = {'label': k + '--' + task_content[k]['name'],
               'task_type': int(k),
               'detail_type': task_content[k]['detail_type']}
        task_label_list.append(tmp)

        detail_type = str(task_content[k]['detail_type'])
        if detail_type != '' and detail_type != '10':
            task_cp_detail_list[k] = detail_content[detail_type]

    result['task_label_list'] = task_label_list
    result['task_content'] = task_content
    result['detail_content'] = detail_content
    result['task_cp_detail_list'] = task_cp_detail_list

    return jsonify(result)

@app.route('/continuous_activities_proj_action', methods=['GET', 'POST'])
def continuous_activities_proj_action():
    update_data = json.loads(request.data)
    result = {'msg': '成功','ret':0}
    _type = update_data['type']
    project = update_data['project']
    project_data = ContinuousActivitiesProj.query.filter_by(project=project).first()

    if _type == 'remark':
        project_data.remark = update_data['remark']
        db.session.commit()

    elif _type == 'clone':
        new_project_data = ContinuousActivitiesProj(
            basic=project_data.basic,
            localization=project_data.localization,
            top_reward=project_data.top_reward,
            task_chest_reward=project_data.task_chest_reward,
            task_group=project_data.task_group,
            remark=project_data.remark)
        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if (new_project_id is None):
            result = {'msg': '克隆失败','ret':2}
        else:
            result = {'msg': '克隆成功','ret':0}

    elif _type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = ContinuousActivitiesProj.query.filter_by(project=project).first()
        if (new_project_data is None):
            result = {'msg': '删除成功','ret':0}
        else:
            result = {'msg': '删除失败','ret':1}

    elif _type == 'basic':
        basic = json.loads(project_data.basic)
        task_group = json.loads(project_data.task_group)
        basic['task_num'] = 0
        for i in range(len(task_group)):
            for ii in range(len(task_group[i]['task'])):
                basic['task_num'] += len(task_group[i]['task'][ii]['task_item'])

        if 'calendar_doc_id' not in basic:
            basic['calendar_doc_id'] = 1

        if '_tag' not in basic:
            basic['_tag'] = []

        doc_content = GetDocByFilename('multiday_event')
        doc_id_list = []
        for k, v in doc_content.items():
            doc_id_list.append({
                'value': int(k),
                'label': '{0}-{1}'.format(k, v['title'])
                })

        result['basic_data'] = basic
        result['doc_id_list'] = doc_id_list

    elif _type == 'update_basic':
        basic = update_data['basic_data']
        project_data.basic = json.dumps(basic)
        db.session.commit()

    elif _type == 'task_chest_reward':
        reward_item_list = rewardList()
        reward_item_list = reward_item_list['name']

        task_chest_reward = json.loads(project_data.task_chest_reward)
        top_reward = json.loads(project_data.top_reward)
        result = {'task_chest_reward': RewardShowToDoc(task_chest_reward, reward_item_list),
                  'top_reward': RewardShowToDoc(top_reward, reward_item_list)}

    elif _type == 'update_task_chest_reward':
        task_chest_reward = RewardToTMysqlNew(update_data['task_chest_reward'])
        top_reward = RewardToTMysqlNew(update_data['top_reward'])
        project_data.task_chest_reward = json.dumps(task_chest_reward)
        project_data.top_reward = json.dumps(top_reward)
        db.session.commit()

    elif _type == 'task_group':
        day = int(update_data['day'])
        task = int(update_data['task'])
        task_group = json.loads(project_data.task_group)
        task_item = task_group[day]['task'][task]['task_item']
        result = {}

        reward_item_list = rewardList()
        reward_item_list = reward_item_list['name']

        task_item_list = []
        for i in range(len(task_item)):
            item = task_item[i]
            level = item['detail'][1]
            detail_id = item['detail'][0]
            task_type = item['task_type']
            target = item['target']
            target_unit = item['target_unit'] if 'target_unit' in item else 1
            if 'task_guide' not in item:
                task_guide = 0
            else:
                task_guide = item['task_guide']

            reward = RewardToDic(item['reward'],0,reward_item_list)

            tmp = {'level': level, 'task_type': task_type, 'idx': i,
                   'reward': reward[0], 'target': target,
                   'task_guide': task_guide,
                   'detail_id': detail_id,
                   'target_unit': target_unit}
            task_item_list.append(tmp)

        result['task_item_list'] = task_item_list
        result['project'] = project_data.project

    elif _type == 'update_task_group':
        taskItem = update_data['taskItem']
        day = int(update_data['Dayactive'])
        task = int(update_data['Taskactive'])

        with open(STATIC_PATH + 'continuous_activities_task_content.json', encoding='utf-8') as f:
            content = json.load(f)
        task_content = content['task_type']
        detail_content = content['detail_type']

        for i in range(len(taskItem)):
            node = taskItem[i]
            node['task_id'] = '{0}_{1}_{2}'.format(day, task, i)
            tid_str = str(node['task_type'])
            detail_type = task_content[tid_str]['detail_type']
            op_type = task_content[tid_str]['op_type']
            node['reward'] = RewardToTMysqlNew(node['reward']['reward'])
            if not detail_type:
                detail_id, detail_type = 0, 0
            else:
                detail_id = node['detail_id'] if 'detail_id' in node else 0

            if not task_content[tid_str]['level_flag']:
                level = 0
            else:
                level = node['level'] if 'level' in node else 0

            # 加速道具 统一入分钟
            # if task_content[tid_str]['time_flag']:
            #     node['target'] *= 60
            # A建筑达到x级 为统一配置
            if tid_str == '2':
                level = node['target']

            node['detail'] = [detail_id, level, op_type]
            if 'target_unit' not in node or node['target_unit'] == '':
                node['target_unit'] = 1
            if 'idx' in node:
                del node['idx']
            if 'detail_id' in node:
                del node['detail_id']
            if 'level' in node:
                del node['level']

        task_group = json.loads(project_data.task_group)
        task_group[day]['task'][task]['task_item'] = taskItem
        project_data.task_group = json.dumps(task_group)
        db.session.commit()

    return jsonify(result)

# @app.route('/clean_continuous_localization', methods=['GET'])
# def clean_continuous_localization():
#     for pid in [14, 33]:
#         que = ContinuousActivitiesProj.query.filter_by(project=pid).first()
#         localization = json.loads(que.localization)
#         for v in localization.values():
#             task_group = v['task_group']
#             for node in task_group:
#                 for task_node in node['task']:
#                     if len(task_node['task_item']) != 0:
#                         task_node['task_item'] = []
#         que.localization = json.dumps(localization)
#         db.session.commit()
#     return jsonify({'ret': 0, 'msg': 'success'})

@app.route('/continuous_activities_proj_down/<int:is_push>', methods= ['GET', 'POST'])
def continuous_activities_proj_down(is_push):
    result_data = {}
    with open(STATIC_PATH + 'continuous_activities_task_content.json', encoding='utf-8') as f:
        content = json.load(f)
    task_content = content['task_type']
    detail_content = content['detail_type']

    special_doc = {'42': {'1': '蓝色', '2': '紫色', '3': '金色'},
                   '48': {'1': '紫色', '2': '橙色'},
                   '50': {'1': '紫色', '2': '橙色'}}

    query = ContinuousActivitiesProj.query.all()
    for que in query:
        pid = int(que.project)
        basic = json.loads(que.basic)
        localization = json.loads(que.localization)
        top_reward = json.loads(que.top_reward)
        task_chest_reward = json.loads(que.task_chest_reward)
        task_group = json.loads(que.task_group)

        task_num = 0
        # for i in range(len(task_group)):
        #     for ii in range(len(task_group[i]['task'])):
        #         task_num += len(task_group[i]['task'][ii]['task_item'])
        for day_idx in range(len(task_group)):
            if 'doc' in task_group[day_idx]:
                del task_group[day_idx]['doc']

            for task_idx in range(len(task_group[day_idx]['task'])):
                task_num += len(task_group[day_idx]['task'][task_idx]['task_item'])

                if 'doc' in task_group[day_idx]['task'][task_idx]:
                    del task_group[day_idx]['task'][task_idx]['doc']

                task_list = task_group[day_idx]['task'][task_idx]['task_item']
                for ii in range(len(task_list)):
                    node = task_list[ii]

                    if 'doc' in node:
                        del node['doc']

                    # if 'task_guide' in node:
                    #     del node['task_guide']

                    target = node['target']
                    detail_id = node['detail'][0]
                    level = node['detail'][1]

                    task_type = str(node['task_type'])

                    # 加速类型的单位都按分钟展示，其他默认为1
                    if task_content[task_type]['time_flag']:
                        # node['target_unit'] = 60
                        node['target'] *= node['target_unit']
                    else:
                        node['target_unit'] = 1

                    # task_type = 21 客户端还留着写死/60的逻辑 需要将target_unit重置为1
                    # 20220530 客户端没有修改
                    if node['task_type'] == 21:
                        node['target_unit'] = 1

                    has_string2_doc = False
                    if task_content[task_type]['id_flag']:
                        detail_type = str(task_content[task_type]['detail_type'])
                        has_string2_doc = True
                        for detail_node in detail_content[detail_type]:
                            if detail_node['id'] == detail_id:
                                string2_detail_doc = detail_node['detail_doc']
                                break
                    for i in range(DOC_NUM):
                        lang_id = str(i+1)
                        task_item_doc = task_content[task_type]['task_doc'][lang_id]
                        # if 'STRING0' in task_item_doc:
                        #     task_item_doc = task_item_doc.replace('STRING0', str(target))
                        if 'STRING1' in task_item_doc:
                            if task_type in special_doc:
                                if task_type == '42':
                                    for detail_node in detail_content['6']:
                                        if detail_node['id'] == level:
                                            string1 = detail_node['detail_doc'][lang_id]
                                            task_item_doc = task_item_doc.replace('STRING1', string1)
                                            break
                                elif task_type == '48':
                                    for detail_node in detail_content['11']:
                                        if detail_node['id'] == level:
                                            string1 = detail_node['detail_doc'][lang_id]
                                            task_item_doc = task_item_doc.replace('STRING1', string1)
                                            break
                                elif task_type == '50':
                                    for detail_node in detail_content['12']:
                                        if detail_node['id'] == level:
                                            string1 = detail_node['detail_doc'][lang_id]
                                            task_item_doc = task_item_doc.replace('STRING1', string1)
                                            break

                                task_item_doc = task_item_doc.replace('STRING1', special_doc[task_type][str(level)])
                            else:
                                task_item_doc = task_item_doc.replace('STRING1', str(level))
                        if 'STRING2' in task_item_doc and has_string2_doc:
                            task_item_doc = task_item_doc.replace('STRING2', string2_detail_doc[lang_id])

                        localization[lang_id]['task_group'][day_idx]['task'][task_idx]['task_item'].append(
                            {'doc': task_item_doc})

        first_day_mode = basic['first_day_mode']
        # calendar_doc = 5 if first_day_mode == 0 else 6

        if 'calendar_doc_id' not in basic:
            basic['calendar_doc_id'] = 1

        if first_day_mode == 0:
            calendar_conf = {
                'event_type': 48,
                'event_ui': 1,
                'order': 1,
                'jump': 1,
                'localization': {
                    'title': basic['calendar_doc_id'],
                    'info': basic['calendar_doc_id']
                },
                'reward': top_reward,
                'show_type': 0
            }
        elif first_day_mode == 1:
            calendar_conf = {
                'event_type': 48,
                'event_ui': 2,
                'order': 1,
                'jump': 1,
                'localization': {
                    'title': basic['calendar_doc_id'],
                    'info': basic['calendar_doc_id']
                },
                'reward': top_reward,
                'show_type': 1
            }

        _tag = basic['_tag'] if '_tag' in basic else []

        result_data[str(pid)] = {
            '_tag': _tag,
            'calendar_conf': calendar_conf,
            'basic': {'event_ui': basic['event_ui']}, 'localization': localization,
            'top_reward': top_reward, 'task_day': basic['task_day'],
            'first_day_mode': basic['first_day_mode'],
            'activity_day': basic['activity_day'],
            'show_time': basic['show_time'], 'task_num': task_num,
            'task_group': task_group,
            'task_chest_reward': task_chest_reward
            }

    response = DownLoad('continuous_activities_proj', result_data, is_push)
    return response


@app.route('/customize_iap_project', methods=['GET'])
def customize_iap_project():
    query = CustomizeIapProject.query.order_by('project').all()
    result = []
    for que in query:
        loc = json.loads(que.localization)
        title = loc['1']['title'] if '1' in loc else ''
        tmp = {'project': que.project, 'title': title,
               'remark': que.remark}
        result.append(tmp)
    return jsonify(result)

@app.route('/customize_iap_project_action', methods=['GET', 'POST'])
def customize_iap_project_action():
    update_data = json.loads(request.data)
    result = {'msg': '成功','ret':0}
    _type = update_data['type']
    project = update_data['project']
    project_data = CustomizeIapProject.query.filter_by(project=project).first()

    if _type == 'remark':
        project_data.remark = update_data['remark']
        db.session.commit()

    elif _type == 'clone':
        new_project_data = CustomizeIapProject(
            basic=project_data.basic,
            localization=project_data.localization,
            free_chest_reward=project_data.free_chest_reward,
            chest_config=project_data.chest_config,
            remark=project_data.remark)
        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if (new_project_id is None):
            result = {'msg': '克隆失败','ret':2}
        else:
            result = {'msg': '克隆成功','ret':0}

    elif _type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = CustomizeIapProject.query.filter_by(project=project).first()
        if (new_project_data is None):
            result = {'msg': '删除成功','ret':0}
        else:
            result = {'msg': '删除失败','ret':1}

    elif _type == 'basic':
        basic = json.loads(project_data.basic)
        free_chest_reward = json.loads(project_data.free_chest_reward)

        # 20220713 4.5协议重构
        if 'coupon_class' not in basic:
            basic['coupon_class'] = []
        # 20220728 tab_id改为不默认
        # 20220804 将 tab_id 从协议中废弃
        # if 'tab_id' not in basic:
        #     basic['tab_id'] = 1
        sub_game_content = loadSubGame()
        sub_game_coupon_config = sub_game_content['sub_game_coupon_config']
        coupon_list = []
        filter_coupon_class = []
        for k, v in sub_game_coupon_config.items():
            if v['class'] in filter_coupon_class:
                continue
            tmp = {'label': str(v['class']),
                   'value': v['class'],
                   'idx': int(k)}
            coupon_list.append(tmp)
            filter_coupon_class.append(v['class'])

        result['basic_data'] = basic
        result['free_chest_reward'] = free_chest_reward
        result['coupon_list'] = coupon_list

    elif _type == 'update_basic':
        basic = update_data['basic_data']
        free_chest_reward = update_data['free_chest_reward']
        project_data.basic = json.dumps(basic)
        project_data.free_chest_reward = json.dumps(free_chest_reward)
        db.session.commit()

    elif _type == 'chest_config':
        chest_config = json.loads(project_data.chest_config)
        for i in range(5):
            if str(i) not in chest_config:
                chest_config[str(i)] = {'customize_reward': []}
        for v in chest_config.values():
            for i in range(len(v['customize_reward'])):
                node = v['customize_reward'][i]
                node['idx'] = i

        with open(STATIC_PATH + 'customize_iap_label.json', encoding='utf-8') as f:
            value_tag_list = json.load(f)

        result['chest_config'] = chest_config
        result['value_tag_list'] = value_tag_list

    elif _type == 'update_chest_config':
        chest_config = update_data['chest_config']
        for v in chest_config.values():
            for node in v['customize_reward']:
                if 'idx' in node:
                    del node['idx']

        project_data.chest_config = json.dumps(chest_config)
        db.session.commit()

    return jsonify(result)

@app.route('/customize_iap_project_down/<int:is_push>', methods= ['GET', 'POST'])
def customize_iap_project_down(is_push):
    result_data = {}

    with open(STATIC_PATH + 'customize_iap_gem_gift.json', encoding='utf-8') as f:
        iap_gem_gift = json.load(f)

    query = CustomizeIapProject.query.order_by('project').all()
    for que in query:
        pid = str(que.project)
        basic = json.loads(que.basic)
        localization = json.loads(que.localization)
        free_chest_reward = json.loads(que.free_chest_reward)
        chest_config = json.loads(que.chest_config)
        remark = que.remark

        free_chest_reward = RewardToTMysqlNew(free_chest_reward)
        new_chest_config = []
        chest_list = []
        for k in chest_config.keys():
            chest_list.append(int(k))
        chest_list.sort()
        for i in chest_list:
            node = chest_config[str(i)]
            if len(node['customize_reward']) == 0 and (
                'gems' not in node or node['gems'] == ''):
                continue

            gems = node['gems']
            al_gift_reward = iap_gem_gift[str(gems)]
            node['al_gift_reward'] = al_gift_reward

            new_customize_reward = []
            for reward_node in node['customize_reward']:
                new_customize_reward.append(RewardToTMysqlNew(reward_node['reward']))
            node['customize_reward'] = new_customize_reward
            node['chest_id'] = i+1

            new_chest_config.append(node)

        # 20220728 修改 tab_id 为填写状态
        # 20220804 将 tab_id 从协议中废弃
        # tab_id = basic['tab_id'] if 'tab_id' in basic else 1
        # 20220729 info 中增加 iap_pid = 2592 固定字段
        iap_pid = 2592

        result_data[pid] = {
            'basic': {'event_ui': basic['event_ui'],
                      'limit_buy_refresh': basic['limit_buy_refresh']},
            'info': {'iap_pid': iap_pid,
                     'doc_id': basic['doc_id'],
                     'free_chest_reward': free_chest_reward,
                     'chest_config': new_chest_config,
                     'coupon_class': basic['coupon_class']},
            'remark': remark}

    response = DownLoad('customize_iap_project', result_data, is_push)
    return response


@app.route('/score_theme_battle_pass_score_config', methods=['GET', 'POST'])
def score_theme_battle_pass_score_config():
    update_data = json.loads(request.data)
    result = {'ret': 0, 'msg': '成功'}
    _type = update_data['type']
    if _type == 'init':
        # score_bp_card_type_list.json task_id
        open_detail_ids = [2, 6, 7, 13, 14, 17, 23]
        open_detail_levels = [2]
        query = ScoreThemeBattlePassScoreConfig.query.order_by('id').all()
        task_list = []
        idx = 0
        for que in query:
            _id = que.id
            task_type = que.task_type
            target = que.target
            target_unit = que.target_unit
            detail_id = que.detail_id
            detail_level = que.detail_level
            remark = que.remark
            score = que.score
            doc_id = que.doc_id
            task_list.append({'id': _id,
                              'task_type': task_type,
                              'target': target,
                              'target_unit': target_unit,
                              'detail_id': detail_id,
                              'detail_level': detail_level,
                              'remark': remark,
                              'score': score,
                              'doc_id': doc_id,
                              'idx': idx})
            idx += 1
        max_idx = len(task_list)
        score_type_dict = score_bp_score_type_list()
        # result['task_type_list'] = score_type_dict['task_type_list']
        # result['detail_type_list'] = score_type_dict['detail_type_list']
        result['task_type_list'] = score_type_dict
        result['task_list'] = task_list
        result['max_idx'] = max_idx
        result['open_detail_ids'] = open_detail_ids
        result['open_detail_levels'] = open_detail_levels
        return jsonify(result)

    elif _type == 'update':
        _id = int(update_data['id'])
        task_type = update_data['task_type']
        target = update_data['target']
        target_unit = update_data['target_unit']
        detail_id = update_data['detail_id']
        detail_level = update_data['detail_level']
        remark = update_data['remark']
        score = update_data['score']
        doc_id = update_data['doc_id']
        # 新增
        if _id == -1:
            new_node = ScoreThemeBattlePassScoreConfig(
                task_type=task_type,
                target=target,
                target_unit=target_unit,
                detail_id=detail_id,
                detail_level=detail_level,
                score=score,
                remark=remark,
                doc_id=doc_id)
            db.session.add(new_node)
            db.session.commit()
            new_node_id = new_node.id
            result['id'] = new_node_id

        else:
            que = ScoreThemeBattlePassScoreConfig.query.filter_by(id=_id).first()
            que_id = que.id
            que.task_type = task_type
            que.target = target
            que.target_unit = target_unit
            que.detail_id = detail_id
            que.detail_level = detail_level
            que.remark = remark
            que.score = score
            que.doc_id = doc_id
            db.session.commit()
            result['id'] = que_id
        return jsonify(result)

    elif _type == 'delete':
        _id = int(update_data['id'])
        que = ScoreThemeBattlePassScoreConfig.query.filter_by(id=_id).first()
        db.session.delete(que)
        db.session.commit()
        check_que = ScoreThemeBattlePassScoreConfig.query.filter_by(id=_id).first()
        if (check_que is None):
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}
        return jsonify(result)

@app.route('/score_theme_battle_pass_project', methods=['GET'])
def score_theme_battle_pass_project():
    query = ScoreThemeBattlePassProject.query.order_by('project').all()
    result = []
    for que in query:
        project = int(que.project)
        localization = json.loads(que.localization)
        title = localization['1']['title'] if '1' in localization else '未填写'
        tmp = {"project": project,'remark': que.remark, 'title': title}
        result.append(tmp)
    return jsonify(result)

@app.route('/score_theme_battle_pass_project_action', methods=['POST'])
def score_theme_battle_pass_project_action():
    update_data = json.loads(request.data)
    result = {'msg': '成功', 'ret': 0}
    _type = update_data['type']
    project = update_data['project']

    project_data = ScoreThemeBattlePassProject.query.filter_by(project=project).first()

    if _type == 'remark':
        remark = update_data['remark']
        project_data.remark = str(remark)
        db.session.commit()

    elif _type == 'clone':
        new_project_data = ScoreThemeBattlePassProject(
            basic=project_data.basic,
            localization=project_data.localization,
            unlock_item_id=project_data.unlock_item_id,
            task=project_data.task,
            score_reward=project_data.score_reward,
            instant_reward=project_data.instant_reward,
            task_extra_reward=project_data.task_extra_reward,
            max_task_id=project_data.max_task_id,
            remark=project_data.remark)

        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if (new_project_id is None):
            result = {'msg': '克隆失败', 'ret': 2}
        else:
            result = {'msg': '克隆成功', 'ret': 0}

    elif _type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = ScoreThemeBattlePassProject.query.filter_by(project=project).first()
        if (new_project_data is None):
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}

    elif _type == 'basic':
        basic_data = json.loads(project_data.basic)
        unlock_item_id = project_data.unlock_item_id
        localization = json.loads(project_data.localization)
        basic_data['unlock_item_id'] = unlock_item_id

        # 20220628 evnet_ui 固定为1
        basic_data['event_ui'] = 1

        if 'iap_id' in basic_data:
            iap_id = basic_data['iap_id']
            line_iap = iap_id // 1000
            sub_line_iap = iap_id % 1000
            basic_data['line_iap'] = line_iap
            basic_data['sub_line_iap'] = sub_line_iap
            del basic_data['iap_id']

        with open(IAP_THEME_LINE_PATH + 'iap_theme_line.json.new', encoding='utf-8') as f:
            content = json.load(f)
        line_list = []
        sub_line_dict = {}
        for k, v in content.items():
            line_tmp = {'value': int(k), 'label': '{0}--{1}'.format(k, v['name'])}
            line_list.append(line_tmp)
            sub_line_dict[k] = []
            for sub_k, sub_v in v['line'].items():
                sub_line_tmp = {'value': int(sub_k),
                                'label': '{0}--{1}'.format(sub_k, sub_v['name'])}
                sub_line_dict[k].append(sub_line_tmp)

        with open(STATIC_PATH + 'theme_battle_pass_label_token.json', encoding='utf-8') as f:
            label_token_content = json.load(f)
        value_tag_list = label_token_content['value_tags']
        token_list = label_token_content['tokens']

        # doc_list = [str(i + 1) for i in range(21)]
        # # doc_name = ['英语', '德语', '法语', '葡语', '西语', '俄语', '简中',
        #             '繁中', '印尼语', '越南语', '泰语', '乌克兰语', '韩语', '土耳其语',
        #             '意大利语', '日语', '马来语', '波兰语', '荷兰语', '罗马尼亚语', '捷克语']
        # doc_name_list = []
        # for i in range(len(doc_list)):
        #     lang_id = doc_list[i]
        #     if lang_id not in localization:
        #         localization[lang_id] = {'title': '未填写' + lang_id,
        #                                  'tab_title': '未填写' + lang_id,
        #                                  'info': '未填写' + lang_id}
        #     doc_name_list.append({'label': doc_name[i], 'value': lang_id})

        result['basic_data'] = basic_data
        # result['localization'] = localization
        result['line_list'] = line_list
        result['sub_line_dict'] = sub_line_dict
        result['value_tag_list'] = value_tag_list
        result['token_list'] = token_list
        # result['doc_name_list'] = doc_name_list

    elif _type == 'update_basic':
        basic = update_data['basic_data']
        unlock_item_id = basic['unlock_item_id']
        del basic['unlock_item_id']
        basic['iap_id'] = basic['line_iap'] * 1000 + basic['sub_line_iap']
        del basic['line_iap']
        del basic['sub_line_iap']

        project_data.basic = json.dumps(basic)
        project_data.unlock_item_id = int(unlock_item_id)
        db.session.commit()

    elif _type == 'score_reward':
        score_reward = json.loads(project_data.score_reward)
        for i in range(len(score_reward)):
            score_reward[i]['idx'] = i
        result['score_reward'] = score_reward

    elif _type == 'update_score_reward':
        score_reward = update_data['score_reward']
        for node in score_reward:
            if 'idx' in node:
                del node['idx']
        project_data.score_reward = json.dumps(score_reward)
        db.session.commit()

    elif _type == 'bp_reward':
        instant_reward = json.loads(project_data.instant_reward)
        task_extra_reward = json.loads(project_data.task_extra_reward)
        result['instant_reward'] = instant_reward
        result['task_extra_reward'] = task_extra_reward

    elif _type == 'update_bp_reward':
        instant_reward = update_data['instant_reward']
        task_extra_reward = update_data['task_extra_reward']
        project_data.instant_reward = json.dumps(instant_reward)
        project_data.task_extra_reward = json.dumps(task_extra_reward)
        db.session.commit()

    elif _type == 'task':
        task = json.loads(project_data.task)
        max_task_id = project_data.max_task_id

        # with open(STATIC_PATH + 'score_type_list.json', encoding='utf-8') as f:
        #     content = json.load(f)
        # task_type_list = content['type_list']
        # detail_type_list = {}
        # for x in range(len(task_type_list)):
        #     task_type = str(task_type_list[x]['value'])
        #     id_list = task_type_list[x]['id_list']
        #     if task_type not in detail_type_list:
        #         detail_type_list[task_type] = []
        #     detail_type_list[task_type] = content[id_list]

        task_type_list = []
        score_query = ScoreThemeBattlePassScoreConfig.query.order_by().all()
        for socre_que in score_query:
            _id = socre_que.id
            remark = socre_que.remark
            tmp = {'label': '{0}-{1}'.format(_id, remark),
                   'value': _id}
            task_type_list.append(tmp)

        result['task'] = task
        result['max_task_id'] = max_task_id
        result['task_type_list'] = task_type_list
        # result['detail_type_list'] = detail_type_list

    elif _type == 'update_task':
        task = update_data['task']
        max_task_id = update_data['max_task_id']

        sql_max_task_id = project_data.max_task_id
        if max_task_id > sql_max_task_id:
            project_data.max_task_id = max_task_id

        project_data.task = json.dumps(task)
        db.session.commit()

    return jsonify(result)

@app.route('/score_theme_battle_pass_project_down/<int:is_push>', methods= ['GET', 'POST'])
def score_theme_battle_pass_project_down(is_push):
    result_data = {}
    with open(STATIC_PATH + 'score_bp_card_type_list.json', encoding='utf-8') as f:
        content = json.load(f)

    # with open(STATIC_PATH + 'score_theme_bp_task_doc.json', encoding='utf-8') as f:
    #     task_doc_content = json.load(f)

    query = ScoreThemeBattlePassProject.query.order_by('project').all()
    for que in query:
        pid = str(que.project)
        basic = json.loads(que.basic)
        # 20220610 basic 字段增加 battle_pass_type
        # 20220628 积分制 event_ui 固定为1, 任务制 event_ui 固定为2
        basic['battle_pass_type'] = 1
        basic['event_ui'] = 1

        basic['iap_pid'] = basic['iap_id']
        del basic['iap_id']

        if 'doc_id' not in basic:
            doc_id = 0
        else:
            doc_id = basic['doc_id']
            del basic['doc_id']

        localization = {
            "title": doc_id,
            "tab_title": doc_id,
            "info": doc_id,
            "task_doc": {}
        }

        # localization = json.loads(que.localization)
        unlock_item_id = que.unlock_item_id
        task = json.loads(que.task)
        score_reward = json.loads(que.score_reward)
        instant_reward = json.loads(que.instant_reward)
        task_extra_reward = json.loads(que.task_extra_reward)

        for i in range(len(score_reward)):
            node = score_reward[i]
            node['reward'] = RewardToTMysqlNew(node['reward'])
            # 20220621 取消加入钥匙奖励
            # node['reward'].append({'a': [0, unlock_item_id, 1]})
            # score 修改为 target, 新增 task_id 字段
            score_reward[i]['target'] = score_reward[i]['score']
            del score_reward[i]['score']
            score_reward[i]['task_id'] = 10000+i
        instant_reward = RewardToTMysqlNew(instant_reward)
        task_extra_reward = RewardToTMysqlNew(task_extra_reward)

        new_task = []
        for node in task:
            score_type = node['task_type']
            score_que = ScoreThemeBattlePassScoreConfig.query.filter_by(id=score_type).first()
            score_task_id = score_que.task_type
            score_target = score_que.target
            score_target_unit = score_que.target_unit
            score_detail_id = score_que.detail_id
            score_detail_level = score_que.detail_level
            score_score = score_que.score
            doc_id = score_que.doc_id
            for score_type_node in content:
                if score_task_id == score_type_node['task_id']:
                    score_task_type = score_type_node['task_type']
                    score_op_type = score_type_node['op_type']
            # 20220624 加速类的target和target_unit保持一致
            if score_task_type in [39, 40, 41]:
                score_target = score_target_unit
            tmp = {'task_id': node['task_id'],
                   'task_type': score_task_type,
                   'target': score_target,
                   'target_unit': score_target_unit,
                   'detail': [score_detail_id,
                              score_detail_level,
                              score_op_type],
                   'reward': [], # 20220610 增加
                   'score': score_score}
            new_task.append(tmp)

            # 在此处理文案 task_doc
            # 20220609 loc字段没有了lang_id
            if 'task_doc' not in localization:
                localization['task_doc'] = {}
            localization['task_doc'][str(node['task_id'])] = doc_id

        result_data[pid] = {'basic': basic,
                            'localization': localization,
                            'unlock_item_id': unlock_item_id,
                            'task': new_task,
                            'score_reward': score_reward,
                            'bp_reward': {
                                'instant_reward': instant_reward,
                                'task_extra_reward': task_extra_reward
                            }}

    # 处理任务制
    with open(STATIC_PATH + 'task_bp_card_type_list.json', encoding='utf-8') as f:
        content = json.load(f)

    # with open(STATIC_PATH + 'task_theme_bp_task_doc.json', encoding='utf-8') as f:
    #     task_doc_content = json.load(f)

    query = TaskThemeBattlePassProject.query.order_by('project').all()
    for que in query:
        pid = str(que.project)
        basic = json.loads(que.basic)
        # 20220610 basic 字段增加 battle_pass_type
        # 20220628 积分制 event_ui 固定为1, 任务制 event_ui 固定为2
        basic['battle_pass_type'] = 0
        basic['event_ui'] = 2

        if 'doc_id' not in basic:
            doc_id = 0
        else:
            doc_id = basic['doc_id']
            del basic['doc_id']

        basic['iap_pid'] = basic['iap_id']
        del basic['iap_id']

        localization = {
            "title": doc_id,
            "tab_title": doc_id,
            "info": doc_id,
            "task_doc": {}
        }
        # localization = json.loads(que.localization)
        unlock_item_id = que.unlock_item_id
        task = json.loads(que.task)
        instant_reward = json.loads(que.instant_reward)
        task_extra_reward = json.loads(que.task_extra_reward)

        instant_reward = RewardToTMysqlNew(instant_reward)
        task_extra_reward = RewardToTMysqlNew(task_extra_reward)

        new_task = []
        for node in task:
            node['reward'] = RewardToTMysqlNew(node['reward'])
            # 20220621 取消加入钥匙奖励
            # node['reward'].append({'a': [0, unlock_item_id, 1]})
            task_type = node['task_type']
            score_que = TaskThemeBattlePassScoreConfig.query.filter_by(id=task_type).first()
            score_task_id = score_que.task_type
            score_target = score_que.target
            score_target_unit = score_que.target_unit
            score_detail_id = score_que.detail_id
            score_detail_level = score_que.detail_level
            doc_id = score_que.doc_id

            for score_type_node in content:
                if score_task_id == score_type_node['task_id']:
                    score_task_type = score_type_node['task_type']
                    score_op_type = score_type_node['op_type']

            tmp = {'task_id': node['task_id'],
                   'task_type': score_task_type,
                   'target': score_target * score_target_unit,
                   'target_unit': score_target_unit,
                   'detail': [score_detail_id,
                              score_detail_level,
                              score_op_type],
                   'reward': node['reward'],
                   'score': 0 } # 20220610 新增
            new_task.append(tmp)

            # 在此处理文案 task_doc
            # 20220609 loc字段没有了lang_id
            if 'task_doc' not in localization:
                localization['task_doc'] = {}
            localization['task_doc'][str(node['task_id'])] = doc_id

        result_data[pid] = {'basic': basic,
                            'localization': localization,
                            'unlock_item_id': unlock_item_id,
                            'task': new_task,
                            'score_reward': [], # 20220610 新增
                            'bp_reward': {
                                'instant_reward': instant_reward,
                                'task_extra_reward': task_extra_reward
                            }}

    response = DownLoad('theme_battle_pass_project', result_data, is_push)
    return response


@app.route('/task_theme_battle_pass_project', methods=['GET'])
def task_theme_battle_pass_project():
    query = TaskThemeBattlePassProject.query.order_by('project').all()
    result = []
    for que in query:
        project = int(que.project)
        localization = json.loads(que.localization)
        title = localization['1']['title'] if '1' in localization else '未填写'
        tmp = {"project": project,'remark': que.remark, 'title': title}
        result.append(tmp)
    return jsonify(result)

@app.route('/task_theme_battle_pass_score_config', methods=['GET', 'POST'])
def task_theme_battle_pass_score_config():
    update_data = json.loads(request.data)
    result = {'ret': 0, 'msg': '成功'}
    _type = update_data['type']
    if _type == 'init':
        open_detail_ids = [21]
        open_detail_levels = []
        query = TaskThemeBattlePassScoreConfig.query.order_by('id').all()
        task_list = []
        idx = 0
        for que in query:
            _id = que.id
            task_type = que.task_type
            target = que.target
            target_unit = que.target_unit
            detail_id = que.detail_id
            detail_level = que.detail_level
            remark = que.remark
            doc_id = que.doc_id
            task_list.append({'id': _id,
                              'task_type': task_type,
                              'target': target,
                              'target_unit': target_unit,
                              'detail_id': detail_id,
                              'detail_level': detail_level,
                              'remark': remark,
                              'doc_id': doc_id,
                              'idx': idx})
            idx += 1
        max_idx = len(task_list)
        score_type_dict = task_bp_score_type_list()
        # result['task_type_list'] = score_type_dict['task_type_list']
        # result['detail_type_list'] = score_type_dict['detail_type_list']
        result['task_type_list'] = score_type_dict
        result['task_list'] = task_list
        result['max_idx'] = max_idx
        result['open_detail_ids'] = open_detail_ids
        result['open_detail_levels'] = open_detail_levels
        return jsonify(result)

    elif _type == 'update':
        _id = int(update_data['id'])
        task_type = update_data['task_type']
        target = update_data['target']
        target_unit = update_data['target_unit']
        detail_id = update_data['detail_id']
        detail_level = update_data['detail_level']
        remark = update_data['remark']
        doc_id = update_data['doc_id']
        # 新增
        if _id == -1:
            new_node = TaskThemeBattlePassScoreConfig(
                task_type=task_type,
                target=target,
                target_unit=target_unit,
                detail_id=detail_id,
                detail_level=detail_level,
                remark=remark,doc_id=doc_id)
            db.session.add(new_node)
            db.session.commit()
            new_node_id = new_node.id
            result['id'] = new_node_id
        else:
            que = TaskThemeBattlePassScoreConfig.query.filter_by(id=_id).first()
            que_id = que.id
            que.task_type = task_type
            que.target = target
            que.target_unit = target_unit
            que.detail_id = detail_id
            que.detail_level = detail_level
            que.remark = remark
            que.doc_id = doc_id
            db.session.commit()
            result['id'] = que_id
        return jsonify(result)

    elif _type == 'delete':
        _id = int(update_data['id'])
        que = TaskThemeBattlePassScoreConfig.query.filter_by(id=_id).first()
        db.session.delete(que)
        db.session.commit()
        check_que = TaskThemeBattlePassScoreConfig.query.filter_by(id=_id).first()
        if (check_que is None):
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}
        return jsonify(result)

@app.route('/task_theme_battle_pass_project_action', methods=['POST'])
def task_theme_battle_pass_project_action():
    update_data = json.loads(request.data)
    result = {'msg': '成功', 'ret': 0}
    _type = update_data['type']
    project = update_data['project']

    project_data = TaskThemeBattlePassProject.query.filter_by(project=project).first()

    if _type == 'remark':
        remark = update_data['remark']
        project_data.remark = str(remark)
        db.session.commit()

    elif _type == 'clone':
        new_project_data = TaskThemeBattlePassProject(
            basic=project_data.basic,
            localization=project_data.localization,
            unlock_item_id=project_data.unlock_item_id,
            task=project_data.task,
            instant_reward=project_data.instant_reward,
            task_extra_reward=project_data.task_extra_reward,
            max_task_id=project_data.max_task_id,
            remark=project_data.remark)

        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if (new_project_id is None):
            result = {'msg': '克隆失败', 'ret': 2}
        else:
            result = {'msg': '克隆成功', 'ret': 0}

    elif _type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = TaskThemeBattlePassProject.query.filter_by(project=project).first()
        if (new_project_data is None):
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}

    elif _type == 'basic':
        basic_data = json.loads(project_data.basic)
        unlock_item_id = project_data.unlock_item_id
        localization = json.loads(project_data.localization)
        basic_data['unlock_item_id'] = unlock_item_id

        # 20220628 event_ui 固定为2
        basic_data['event_ui'] = 2

        if 'iap_id' in basic_data:
            iap_id = basic_data['iap_id']
            line_iap = iap_id // 1000
            sub_line_iap = iap_id % 1000
            basic_data['line_iap'] = line_iap
            basic_data['sub_line_iap'] = sub_line_iap
            del basic_data['iap_id']

        with open(IAP_THEME_LINE_PATH + 'iap_theme_line.json.new', encoding='utf-8') as f:
            content = json.load(f)
        line_list = []
        sub_line_dict = {}
        for k, v in content.items():
            line_tmp = {'value': int(k), 'label': '{0}--{1}'.format(k, v['name'])}
            line_list.append(line_tmp)
            sub_line_dict[k] = []
            for sub_k, sub_v in v['line'].items():
                sub_line_tmp = {'value': int(sub_k),
                                'label': '{0}--{1}'.format(sub_k, sub_v['name'])}
                sub_line_dict[k].append(sub_line_tmp)

        with open(STATIC_PATH + 'theme_battle_pass_label_token.json', encoding='utf-8') as f:
            label_token_content = json.load(f)
        value_tag_list = label_token_content['value_tags']
        token_list = label_token_content['tokens']

        doc_list = [str(i + 1) for i in range(21)]
        doc_name = ['英语', '德语', '法语', '葡语', '西语', '俄语', '简中',
                    '繁中', '印尼语', '越南语', '泰语', '乌克兰语', '韩语', '土耳其语',
                    '意大利语', '日语', '马来语', '波兰语', '荷兰语', '罗马尼亚语', '捷克语']
        doc_name_list = []
        for i in range(len(doc_list)):
            lang_id = doc_list[i]
            if lang_id not in localization:
                localization[lang_id] = {'title': '未填写' + lang_id,
                                         'tab_title': '未填写' + lang_id,
                                         'info': '未填写' + lang_id}
            doc_name_list.append({'label': doc_name[i], 'value': lang_id})

        result['basic_data'] = basic_data
        result['localization'] = localization
        result['line_list'] = line_list
        result['sub_line_dict'] = sub_line_dict
        result['value_tag_list'] = value_tag_list
        result['token_list'] = token_list
        result['doc_name_list'] = doc_name_list

    elif _type == 'update_basic':
        basic = update_data['basic_data']
        unlock_item_id = basic['unlock_item_id']
        del basic['unlock_item_id']
        basic['iap_id'] = basic['line_iap'] * 1000 + basic['sub_line_iap']
        del basic['line_iap']
        del basic['sub_line_iap']

        project_data.basic = json.dumps(basic)
        project_data.unlock_item_id = int(unlock_item_id)
        db.session.commit()

    elif _type == 'bp_reward':
        instant_reward = json.loads(project_data.instant_reward)
        task_extra_reward = json.loads(project_data.task_extra_reward)
        result['instant_reward'] = instant_reward
        result['task_extra_reward'] = task_extra_reward

    elif _type == 'update_bp_reward':
        instant_reward = update_data['instant_reward']
        task_extra_reward = update_data['task_extra_reward']
        project_data.instant_reward = json.dumps(instant_reward)
        project_data.task_extra_reward = json.dumps(task_extra_reward)
        db.session.commit()

    elif _type == 'task':
        task = json.loads(project_data.task)
        max_task_id = project_data.max_task_id

        # with open(STATIC_PATH + 'score_type_list.json', encoding='utf-8') as f:
        #     content = json.load(f)
        # task_type_list = content['type_list']
        # detail_type_list = {}
        # for x in range(len(task_type_list)):
        #     task_type = str(task_type_list[x]['value'])
        #     id_list = task_type_list[x]['id_list']
        #     if task_type not in detail_type_list:
        #         detail_type_list[task_type] = []
        #     detail_type_list[task_type] = content[id_list]
        for i in range(len(task)):
            node = task[i]
            node['idx'] = i
        task_type_list = []
        query = TaskThemeBattlePassScoreConfig.query.order_by('id').all()
        for que in query:
            tmp = {'label': '{0}--{1}'.format(que.id, que.remark),
                   'value': int(que.id)}
            task_type_list.append(tmp)

        result['task'] = task
        result['max_task_id'] = max_task_id
        result['task_type_list'] = task_type_list
        # result['task_type_list'] = content['type_list']
        # result['detail_type_list'] = detail_type_list

    elif _type == 'update_task':
        task = update_data['task']
        max_task_id = update_data['max_task_id']

        for node in task:
            if 'idx' in node:
                del node['idx']

        sql_max_task_id = project_data.max_task_id
        if max_task_id > sql_max_task_id:
            project_data.max_task_id = max_task_id

        project_data.task = json.dumps(task)
        db.session.commit()

    return jsonify(result)


@app.route('/gold_rush_project', methods=['GET'])
def gold_rush_project():
    query = GoldRushProject.query.order_by('project').all()
    result = []
    for que in query:
        project = int(que.project)
        basic = json.loads(que.basic)
        title = basic['doc_id'] if 'doc_id' in basic else '未填写doc_id'
        tmp = {"project": project,'remark': que.remark, 'title': title}
        result.append(tmp)
    return jsonify(result)

@app.route('/gold_rush_project_action', methods=['POST'])
def gold_rush_project_action():
    update_data = json.loads(request.data)
    result = {'msg': '成功', 'ret': 0}
    _type = update_data['type']
    project = update_data['project']

    project_data = GoldRushProject.query.filter_by(project=project).first()

    if _type == 'remark':
        remark = update_data['remark']
        project_data.remark = str(remark)
        db.session.commit()

    elif _type == 'clone':
        new_project_data = GoldRushProject(
            basic=project_data.basic,
            localization=project_data.localization,
            task_group=project_data.task_group,
            score_rule=project_data.score_rule,
            max_task_num=project_data.max_task_num,
            remark=project_data.remark)

        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if (new_project_id is None):
            result = {'msg': '克隆失败', 'ret': 2}
        else:
            result = {'msg': '克隆成功', 'ret': 0}

    elif _type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = GoldRushProject.query.filter_by(project=project).first()
        if (new_project_data is None):
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}

    elif _type == 'basic':
        basic_data = json.loads(project_data.basic)
        result['basic_data'] = basic_data

    elif _type == 'update_basic':
        basic = update_data['basic_data']
        project_data.basic = json.dumps(basic)
        db.session.commit()

    elif _type == 'task_group':
        """
        task_group = [{...}, {...}, ...]
        """
        schedule_data = read_s3_file('gold_rush_schedule')
        cur_time = int(time.time())
        activate = 0
        for node in schedule_data:
            # 生效，且使用了此pid，activate = 1
            if node['begin_time'] <= cur_time <= node['end_time']:
                if int(project) == node['pid'] or int(project) in node['special_pid']['pid_list']:
                    activate = 1
                    break

        task_group = json.loads(project_data.task_group)
        score_rule = project_data.score_rule
        max_task_num = project_data.max_task_num

        result['task_group'] = task_group
        result['score_rule'] = score_rule
        result['max_task_num'] = max_task_num
        result['activate'] = activate

    elif _type == 'update_task_group':
        task_group = update_data['task_group']
        score_rule = update_data['score_rule']
        max_task_num = int(update_data['max_task_num'])
        sql_max_task_num = project_data.max_task_num

        project_data.task_group = json.dumps(task_group)
        project_data.score_rule = score_rule
        if max_task_num > sql_max_task_num:
            project_data.max_task_num = max_task_num
        db.session.commit()

    return jsonify(result)

@app.route('/gold_rush_project_down/<int:is_push>', methods= ['GET', 'POST'])
def gold_rush_project_down(is_push):
    result_data = {}

    query = GoldRushProject.query.order_by('project').all()
    for que in query:
        pid = str(que.project)
        basic = json.loads(que.basic)
        localization = json.loads(que.localization)
        task_group = json.loads(que.task_group)
        score_rule = int(que.score_rule)
        remark = str(que.remark)

        # score_icon 改名为 score_id
        basic['score_id'] = basic['score_icon']
        del basic['score_icon']

        doc_id = basic['doc_id']
        task_doc_id = basic['task_doc_id']
        del basic['doc_id'], basic['task_doc_id']
        localization = {'title': doc_id, 'event_title': doc_id,
                        'info': doc_id, 'task_doc': {}}

        new_task_group = [[]]
        for node in task_group:
            node['reward'] = RewardToTMysqlNew(node['reward'])
            node['task_type'] = 78
            node['task_unit'] = 1
            node['detail'] = [-1, 0, 2]
            # node['id_list'] = []
            # node['num'] = 1
            # node['score'] = score_rule
            node['target_unit'] = 1
            new_task_group[0].append(node)

            if 'modify' in node:
                del node['modify']

            localization['task_doc'][str(node['task_id'])] = task_doc_id

        basic['u_score'] = score_rule
        basic['iap_pid_list'] = [-1]

        result_data[pid] = {'basic': basic,
                            'localization': localization,
                            'task_group': new_task_group,
                            'remark': remark}

    response = DownLoad('gold_rush_proj', result_data, is_push)
    # 如果发布成功了，需要将 task_group 中的 modefy 删除
    for que in query:
        task_group = json.loads(que.task_group)
        for task_node in task_group:
            if 'modify' in task_node:
                del task_node['modify']
        que.task_group = json.dumps(task_group)
        db.session.commit()
    return response


@app.route('/store_treasure_project', methods=['GET'])
def store_treasure_project():
    query = StoreTreasureProject.query.order_by('project').all()
    result = []
    for que in query:
        project = int(que.project)
        basic = json.loads(que.basic)
        title = basic['doc_id'] if 'doc_id' in basic else '未填写doc_id'
        tmp = {"project": project,'remark': que.remark, 'title': title}
        result.append(tmp)
    return jsonify(result)

@app.route('/store_treasure_project_action', methods=['POST'])
def store_treasure_project_action():
    update_data = json.loads(request.data)
    result = {'msg': '成功', 'ret': 0}
    _type = update_data['type']
    project = update_data['project']

    project_data = StoreTreasureProject.query.filter_by(project=project).first()

    if _type == 'remark':
        remark = update_data['remark']
        project_data.remark = str(remark)
        db.session.commit()

    elif _type == 'clone':
        new_project_data = StoreTreasureProject(
            basic=project_data.basic,
            localization=project_data.localization,
            task_group=project_data.task_group,
            score_rule=project_data.score_rule,
            max_task_num=project_data.max_task_num,
            remark=project_data.remark)

        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if (new_project_id is None):
            result = {'msg': '克隆失败', 'ret': 2}
        else:
            result = {'msg': '克隆成功', 'ret': 0}

    elif _type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = StoreTreasureProject.query.filter_by(project=project).first()
        if (new_project_data is None):
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}

    elif _type == 'basic':
        basic_data = json.loads(project_data.basic)
        if 'id_list' not in basic_data:
            basic_data['id_list'] = []
        result['basic_data'] = basic_data

    elif _type == 'update_basic':
        basic = update_data['basic_data']
        project_data.basic = json.dumps(basic)
        db.session.commit()

    elif _type == 'task_group':
        """
        task_group = [{...}, {...}, ...]
        """
        schedule_data = read_s3_file('store_treasure_schedule')
        cur_time = int(time.time())
        activate = 0
        for node in schedule_data:
            # 生效，且使用了此pid，activate = 1
            if node['begin_time'] <= cur_time <= node['end_time']:
                if int(project) == node['pid'] or int(project) in node['special_pid']['pid_list']:
                    activate = 1
                    break

        task_group = json.loads(project_data.task_group)
        score_rule = project_data.score_rule
        max_task_num = project_data.max_task_num

        result['task_group'] = task_group
        result['score_rule'] = score_rule
        result['max_task_num'] = max_task_num
        result['activate'] = activate

    elif _type == 'update_task_group':
        task_group = update_data['task_group']
        score_rule = update_data['score_rule']
        max_task_num = int(update_data['max_task_num'])
        sql_max_task_num = project_data.max_task_num

        project_data.task_group = json.dumps(task_group)
        project_data.score_rule = score_rule
        if max_task_num > sql_max_task_num:
            project_data.max_task_num = max_task_num
        db.session.commit()

    return jsonify(result)

@app.route('/store_treasure_project_down/<int:is_push>', methods= ['GET', 'POST'])
def store_treasure_project_down(is_push):
    result_data = {}

    query = StoreTreasureProject.query.order_by('project').all()
    for que in query:
        pid = str(que.project)
        basic = json.loads(que.basic)
        id_list = basic['id_list']
        iap_pid_list = list(map(int, id_list.split(',')))
        del basic['id_list']
        # score_icon 改名为 score_id
        basic['score_id'] = basic['score_icon']
        del basic['score_icon']

        localization = json.loads(que.localization)
        task_group = json.loads(que.task_group)
        score_rule = int(que.score_rule)
        remark = str(que.remark)

        doc_id = basic['doc_id']
        task_doc_id = basic['task_doc_id']
        del basic['doc_id'], basic['task_doc_id']
        localization = {'title': doc_id, 'event_title': doc_id,
                        'info': doc_id, 'task_doc': {}}

        new_task_group = [[]]
        for node in task_group:
            node['reward'] = RewardToTMysqlNew(node['reward'])
            node['task_type'] = 78
            node['task_unit'] = 1
            node['detail'] = [0, 0, 2]
            # node['id_list'] = ld_list
            # node['num'] = 1
            # node['score'] = score_rule
            node['target_unit'] = 1
            new_task_group[0].append(node)

            if 'modify' in node:
                del node['modify']

            localization['task_doc'][str(node['task_id'])] = task_doc_id

        basic['u_score'] = score_rule
        basic['iap_pid_list'] = iap_pid_list

        result_data[pid] = {'basic': basic,
                            'localization': localization,
                            'task_group': new_task_group,
                            'remark': remark}

    response = DownLoad('store_treasure_proj', result_data, is_push)
    # 如果发布成功了，需要将 task_group 中的 modefy 删除
    for que in query:
        task_group = json.loads(que.task_group)
        for task_node in task_group:
            if 'modify' in task_node:
                del task_node['modify']
        que.task_group = json.dumps(task_group)
        db.session.commit()
    return response


@app.route('/shop_project', methods=['GET'])
def shop_project():
    shop_data = ShopProject.query.order_by('project').all()
    result = {}
    data_list = []
    # shop_name_list 用于过滤未存在 shop_name.json 中的商店Pid
    shop_name_list = []
    name_list = [{'shop_name': 'ALL', 'shop_id': 0}]
    with open(STATIC_PATH + 'shop_name.json', encoding='utf-8') as f:
        shop_name_query = json.load(f)
    for que in shop_name_query.values():
        shop_name = que['shop_name']
        shop_id = que['shop_id']
        name_list.append({'shop_name': shop_name,
                          'shop_id': shop_id})
        shop_name_list.append(shop_name)
    name_list.sort(key=lambda x: x['shop_id'])

    for que in shop_data:
        project = int(que.project)
        remark = que.remark
        shop_name = que.shop_name

        if shop_name not in shop_name_list:
            continue

        basic = json.loads(que.basic)
        name = basic['name'] if 'name' in basic.keys() else ''
        tmp = {'project': project, 'remark': remark,
               'shop_name': shop_name, 'name': name}
        data_list.append(tmp)

    result['data_list'] = data_list
    result['name_list'] = name_list

    return jsonify(result)

@app.route('/add_shop_name', methods=['GET', 'POST'])
def add_shop_name():
    if request.method == 'GET':
        return jsonify({'ret': 0, 'msg': 'success'})
    elif request.method == 'POST':
        update_data = json.loads(request.data)
        shop_names = update_data['shop_names']
        content = {}
        for shop in shop_names:
            shop_id = int(shop['shop_id'])
            shop_name = str(shop['shop_name'])
            if shop_name == 'ALL' or shop_id == 0:
                continue
            content[str(shop_id)] = {'shop_id': shop_id,
                                     'shop_name': shop_name}

        with open(STATIC_PATH + 'shop_name.json', 'w', encoding='utf-8') as f:
            f.write(json.dumps(content))

        return jsonify({'ret': 0, 'msg': '添加成功'})

@app.route('/shop_project_action', methods=['GET', 'POST'])
def shop_project_action():
    update_data = json.loads(request.data)
    result = {'msg': '成功', 'ret': 0}
    _type = update_data['type']
    project = update_data['project']
    project_data = ShopProject.query.filter_by(project=project).first()
    if _type == 'remark':
        remark = update_data['remark']
        project_data.remark = remark
        db.session.commit()

    elif _type == 'clone':
        new_project_data = ShopProject(basic = project_data.basic,
                                       title = project_data.title,
                                       goods = project_data.goods,
                                       remark = project_data.remark,
                                       shop_name = project_data.shop_name)
        db.session.add(new_project_data)
        db.session.commit()

        new_project_id = new_project_data.project
        if new_project_id is None:
            result = {'msg': '克隆失败', 'ret': 2}
        else:
            result = {'msg': '克隆成功', 'ret': 0}

    elif _type == 'clone_shop':
        shop_id = int(update_data['shop_id'])
        with open(STATIC_PATH + 'shop_name.json', encoding='utf-8') as f:
            content = json.load(f)
        shop_name = content[str(shop_id)]['shop_name']
        new_project_data = ShopProject(basic = project_data.basic,
                                       title = project_data.title,
                                       goods = project_data.goods,
                                       remark = project_data.remark,
                                       shop_name = shop_name)
        db.session.add(new_project_data)
        db.session.commit()

        new_project_id = new_project_data.project
        if new_project_id is None:
            result = {'msg': '克隆失败', 'ret': 2}
        else:
            result = {'msg': '克隆成功', 'ret': 0}

    elif _type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = ShopProject.query.filter_by(project=project).first()
        if (new_project_data is None):
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}

    elif _type == 'basic':
        basic = json.loads(project_data.basic)
        title = json.loads(project_data.title)
        title_list = []

        doc_name = ['英语', '德语', '法语', '葡语', '西语', '俄语', '简中',
                    '繁中', '印尼语', '越南语', '泰语', '乌克兰语', '韩语',
                    '土耳其语', '意大利语', '日语', '马来语', '波兰语',
                    '荷兰语', '罗马尼亚语', '捷克语']
        doc_langs = [str(i) for i in range(21)]
        doc_name_list = []
        for lang in range(21):
            if str(lang) not in title:
                title[str(lang)] = '未填写'
            doc_name_list.append({'label': doc_name[lang],
                                  'value': str(lang),
                                  'doc': title[str(lang)]
                                  })

        if 'currency' not in basic or basic['currency'] == '':
            basic['currency'] = []
        for i in range(len(basic['currency'])):
            basic['currency'][i]['idx'] = i
        max_currency_idx = len(basic['currency'])

        if '_tag' not in basic:
            basic['_tag'] = []

        basic['title'] = title
        result['basic_data'] = basic
        result['doc_name_list'] = doc_name_list
        result['max_currency_idx'] = max_currency_idx

    elif _type == 'update_basic':
        basic_data = update_data['basic_data']
        if 'title' in basic_data:
            del basic_data['title']
        project_data.basic = json.dumps(basic_data)
        db.session.commit()

    elif _type == 'goods_reward':
        goods = json.loads(project_data.goods)
        max_goods_idx = len(goods)
        for i in range(len(goods)):
            goods[i]['idx'] = i
        result['data_list'] = goods
        result['max_goods_idx'] = max_goods_idx

    elif _type == 'update_goods_reward':
        goods = update_data['data_list']
        for node in goods:
            if 'idx' in node:
                del node['idx']
        project_data.goods = json.dumps(goods)
        db.session.commit()

    return jsonify(result)

@app.route('/shop_schedule', methods=['GET', 'POST'])
def shop_schedule():
    shop_id_list = []
    shop_name_list = []
    shopname_cp_type = {}
    with open(STATIC_PATH + 'shop_name.json', encoding='utf-8') as f:
        content = json.load(f)
    for v in content.values():
        shopname_cp_type[v['shop_name']] = str(v['shop_id'])
        shop_id_list.append(v['shop_id'])
        shop_name_list.append(v['shop_name'])

    shop_type_list = []
    for shop_name, shop_id in shopname_cp_type.items():
        shop_type_list.append({'shop_id': int(shop_id),
                               'shop_name': shop_name})

    shop_data = ShopSchedule.query.order_by('id').all()
    result = {}
    schedule_data = []
    for que in shop_data:
        schedule_que = json.loads(que.data)

        if schedule_que['store_type'] not in shop_id_list:
            continue

        schedule_que['id'] = que.id
        schedule_data.append(schedule_que)

    schedule_data = sorted(schedule_data, key=lambda x: fomat_date_str(x['begin_time']))

    project_data = ShopProject.query.order_by('project').all()
    pid_data = {}
    for que in project_data:
        pid = que.project
        shop_name = que.shop_name

        if shop_name not in shop_name_list:
            continue

        shop_type = shopname_cp_type[shop_name]
        title = json.loads(que.title)
        if '0' in title.keys():
            label = title['0']
        else:
            label = ''
        if shop_type not in pid_data.keys():
            pid_data[shop_type] = []
        tmp = {'value': pid, 'label': label}
        pid_data[shop_type].append(tmp)

    result['schedule_data'] = schedule_data
    result['pid_data'] = pid_data
    result['shop_type_list'] = shop_type_list

    return jsonify(result)

@app.route('/shop_schedule_action', methods=['GET', 'POST'])
def shop_schedule_action():
    update_data = json.loads(request.data)
    result = {'msg': '成功', 'ret': 0}
    _type = update_data['type']
    data_list = update_data['data_list']
    if _type == 'update':
        for node in data_list:
            if 'id' in node.keys():
                mysql_data = json.dumps(node)
                ShopSchedule.query.filter_by(id = int(node['id'])).update({'data': mysql_data})
            else:
                mysql_data = json.dumps(node)
                new_node = ShopSchedule(data=mysql_data)
                db.session.add(new_node)
            db.session.commit()

        shop_project_down(1)

    elif _type == 'delete':
        _id = int(update_data['id'])
        schedule_data = ShopSchedule.query.filter_by(id=_id).first()
        db.session.delete(schedule_data)
        db.session.commit()
        new_project_data = ShopSchedule.query.filter_by(id=_id).first()
        if (new_project_data is None):
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}

    return jsonify(result)

@app.route('/shop_project_down/<int:is_push>', methods=['GET', 'POST'])
def shop_project_down(is_push):
    result_data = {'proj': {}, 'schedule': {}}
    project_data = {}
    schedule_data = {}
    pid_list = []
    cur_time = int(time.time())
    shop_id_list = []
    with open(STATIC_PATH + 'shop_name.json', encoding='utf-8') as f:
        content = json.load(f)
    for v in content.values():
        shop_id_list.append(v['shop_id'])

    empty_store_type_list = [i for i in content.keys()]

    schedule_que = ShopSchedule.query.all()
    for que in schedule_que:
        data = json.loads(que.data)
        if data['store_type'] not in shop_id_list:
            continue
        store_type = str(data['store_type'])
        if store_type not in schedule_data.keys():
            if cur_time <= fomat_date_str(data['end_time']):
                begin_time = fomat_date_str(data['begin_time'])
                end_time = fomat_date_str(data['end_time'])
                sid_list = ToSidList(data['sid_list'])
                schedule_data[store_type] = [
                    {'begin_time': begin_time, 'end_time': end_time,
                     'cycle': data['cycle'], 'pid': data['pid'],
                     'sid_list': sid_list}]
                if int(data['pid']) not in pid_list:
                    pid_list.append(int(data['pid']))

                if store_type in empty_store_type_list:
                    empty_store_type_list.remove(store_type)

        else:
            if cur_time <= fomat_date_str(data['end_time']):
                begin_time = fomat_date_str(data['begin_time'])
                end_time = fomat_date_str(data['end_time'])
                sid_list = ToSidList(data['sid_list'])
                schedule_data[store_type].append(
                    {'begin_time': begin_time, 'end_time': end_time,
                    'cycle': data['cycle'], 'pid': data['pid'],
                     'sid_list': sid_list})
                if int(data['pid']) not in pid_list:
                    pid_list.append(int(data['pid']))

                if store_type in empty_store_type_list:
                    empty_store_type_list.remove(store_type)

    for empty_store_type in empty_store_type_list:
        schedule_data[empty_store_type] = []
    schedule_data = dict(sorted(schedule_data.items(), key=lambda x:int(x[0])))
    result_data['schedule'] = schedule_data

    for pid in pid_list:
        que = ShopProject.query.filter_by(project=pid).first()
        pid_str = str(pid)
        title = json.loads(que.title)
        basic = json.loads(que.basic)
        new_currency = []
        old_currency = basic['currency']
        for node in old_currency:
            new_currency.append([node['coin_type'], node['coin_id']])

        goods = json.loads(que.goods)
        new_goods = [[]]
        for node in goods:
            reward = RewardToTMysqlNew(node['reward'])
            coin_list = RewardToTMysqlNew(node['coin_list'])
            reward.append(node['limit'])
            reward.append(coin_list)
            new_goods[0].append(reward)

        if pid_str not in project_data.keys():
            project_data[pid_str] = {}

        _tag = basic['_tag'] if '_tag' in basic else []

        project_data[pid_str] = {
            '_tag': _tag,
            'castle_lv': basic['castle_lv'], 'ui': basic['ui'],
            'title': title, 'currency': new_currency,
            'goods': new_goods
        }
    result_data['proj'] = project_data

    response = DownLoad('shop', result_data, is_push)
    if is_push == 1:
        genCionExpiredJson(result_data)
    return response


@app.route('/western_shadow_menu_project', methods=['GET'])
def western_shadow_menu_project():
    query = WesternShadowMenuProject.query.order_by('project').all()
    result = []
    for que in query:
        project = int(que.project)
        basic = json.loads(que.basic)
        tmp = {"project": project,'remark': que.remark}
        result.append(tmp)
    return jsonify(result)

@app.route('/western_shadow_menu_project_action', methods=['POST'])
def western_shadow_menu_project_action():
    update_data = json.loads(request.data)
    result = {'msg': '成功', 'ret': 0,}
    _type = update_data['type']
    project = update_data['project']

    project_data = WesternShadowMenuProject.query.filter_by(project=project).first()

    if _type == 'remark':
        remark = update_data['remark']
        project_data.remark = str(remark)
        db.session.commit()

    elif _type == 'clone':
        new_project_data = WesternShadowMenuProject(
            basic=project_data.basic,
            localization=project_data.localization,
            score_type_list=project_data.score_type_list,
            reward=project_data.reward,
            rank_reward_score_limit=project_data.rank_reward_score_limit,
            remark=project_data.remark,
            hosptal=project_data.hosptal,
            max_score_type_id=project_data.max_score_type_id,
            revive=project_data.revive)

        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if (new_project_id is None):
            result = {'msg': '克隆失败', 'ret': 2}
        else:
            result = {'msg': '克隆成功', 'ret': 0}

    elif _type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = WesternShadowMenuProject.query.filter_by(project=project).first()
        if new_project_data is None:
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}

    elif _type == 'basic':
        basic_data = json.loads(project_data.basic)
        if 'top_reward' not in basic_data:
            basic_data['top_reward'] = []
        if '_tag' not in basic_data:
            basic_data['_tag'] = []

        # 20221111 厄运暗影的commom buff是多选
        common_buff_project = read_s3_file('common_buff_project')
        common_buff_list = []
        for node in common_buff_project:
            common_buff_list.append({
                'label': '{0}-{1}'.format(node['value'], node['label']),
                'value': node['value']
                })

        doc_content = GetDocByFilename('doom_event')
        doc_id_list = []
        for k, v in doc_content.items():
            doc_id_list.append({
                'value': int(k),
                'label': '{0}-{1}'.format(k, v['title'])
                })

        result['basic_data'] = basic_data
        result['common_buff_list'] = common_buff_list
        result['doc_id_list'] = doc_id_list

    elif _type == 'update_basic':
        basic_data = update_data['basic_data']
        project_data.basic = json.dumps(basic_data)
        db.session.commit()

    elif _type == 'record_rank_reward':
        reward = json.loads(project_data.reward)
        if 'record_rank_reward' in reward:
            record_rank_reward = reward['record_rank_reward']
        else:
            record_rank_reward = []
        for i in range(len(record_rank_reward)):
            node = record_rank_reward[i]
            node['idx'] = i
        result['record_rank_reward'] = record_rank_reward

    elif _type == 'update_record_rank_reward':
        record_rank_reward = update_data['record_rank_reward']
        for node in record_rank_reward:
            if 'idx' in node:
                del node['idx']
        reward = json.loads(project_data.reward)
        reward['record_rank_reward'] = record_rank_reward
        project_data.reward = json.dumps(reward)
        db.session.commit()
        result['msg'] = '更新成功'

    elif _type == 'xiaoyong_rank_reward':
        reward = json.loads(project_data.reward)
        rank_reward_score_limit = project_data.rank_reward_score_limit
        if 'xiaoyong_rank_reward' in reward:
            xiaoyong_rank_reward = reward['xiaoyong_rank_reward']
        else:
            xiaoyong_rank_reward = []
        for i in range(len(xiaoyong_rank_reward)):
            node = xiaoyong_rank_reward[i]
            node['idx'] = i
        result['xiaoyong_rank_reward'] = xiaoyong_rank_reward
        result['rank_reward_score_limit'] = rank_reward_score_limit

    elif _type == 'update_xiaoyong_rank_reward':
        xiaoyong_rank_reward = update_data['xiaoyong_rank_reward']
        rank_reward_score_limit = update_data['rank_reward_score_limit']
        for node in xiaoyong_rank_reward:
            if 'idx' in node:
                del node['idx']
        reward = json.loads(project_data.reward)
        reward['xiaoyong_rank_reward'] = xiaoyong_rank_reward
        project_data.reward = json.dumps(reward)
        project_data.rank_reward_score_limit = int(rank_reward_score_limit)
        db.session.commit()
        result['msg'] = '更新成功'

    elif _type == 'xiaoyong_goal_reward':
        reward = json.loads(project_data.reward)
        if 'xiaoyong_goal_reward' in reward:
            xiaoyong_goal_reward = reward['xiaoyong_goal_reward']
        else:
            xiaoyong_goal_reward = []
        for i in range(len(xiaoyong_goal_reward)):
            node = xiaoyong_goal_reward[i]
            node['idx'] = i
        result['xiaoyong_goal_reward'] = xiaoyong_goal_reward

    elif _type == 'update_xiaoyong_goal_reward':
        xiaoyong_goal_reward = update_data['xiaoyong_goal_reward']
        for node in xiaoyong_goal_reward:
            if 'idx' in node:
                del node['idx']
        reward = json.loads(project_data.reward)
        reward['xiaoyong_goal_reward'] = xiaoyong_goal_reward
        project_data.reward = json.dumps(reward)
        db.session.commit()
        result['msg'] = '更新成功'

    elif _type == 'xiaoyong_score_type_list':
        xiaoyong_score_type_list = json.loads(project_data.score_type_list)
        for i in range(len(xiaoyong_score_type_list)):
            node = xiaoyong_score_type_list[i]
            node['idx'] = i
            if type(node['id_list']) == list:
                node['id_list'] = node['id_list'][0]

        with open(STATIC_PATH + 'western_shadow_xiaoyong_calc_score.json', encoding='utf-8') as f:
            content = json.load(f)
        total_score_type_list = content['total']
        detail_score_type_dict = content['detail']
        result['total_score_type_list'] = total_score_type_list
        result['detail_score_type_dict'] = detail_score_type_dict
        result['xiaoyong_score_type_list'] = xiaoyong_score_type_list

    elif _type == 'update_xiaoyong_score_type_list':
        xiaoyong_score_type_list = update_data['xiaoyong_score_type_list']
        for node in xiaoyong_score_type_list:
            if 'idx' in node:
                del node['idx']
            node['id_list'] = [node['id_list']]

        project_data.score_type_list = json.dumps(xiaoyong_score_type_list)
        db.session.commit()

        result['msg'] = '更新成功'

    elif _type == 'hospital':
        hosptal = json.loads(project_data.hosptal)
        for i in range(len(hosptal)):
            node = hosptal[i]
            node['idx'] = i
        result['hosptal'] = hosptal

    elif _type == 'update_hosptal':
        hosptal = update_data['hosptal']
        for i in range(len(hosptal)):
            node = hosptal[i]
            if 'idx' in node:
                del node['idx']
        project_data.hosptal = json.dumps(hosptal)
        db.session.commit()
        result['msg'] = '更新成功'

    elif _type == 'revive':
        revive = json.loads(project_data.revive)
        if 'revive_switch' not in revive:
            revive['revive_switch'] = 0
        if 'revive_table' not in revive:
            revive['revive_table'] = []
        else:
            for i in range(len(revive['revive_table'])):
                revive['revive_table'][i]['idx'] = i
        result['revive_switch'] = revive['revive_switch']
        result['revive_table'] = revive['revive_table']

    elif _type == 'update_revive':
        revive_table = update_data['revive_table']
        revive_switch = update_data['revive_switch']
        project_data.revive = json.dumps({
            'revive_table': revive_table,
            'revive_switch': revive_switch
            })
        db.session.commit()
        result['msg'] = '更新成功'

    return jsonify(result)

@app.route('/western_shadow_menu_project_down/<int:is_push>/<int:event_num>', methods=['GET', 'POST'])
def western_shadow_menu_project_down(is_push, event_num):
    menu_result = {}
    record_result = {'event_main_type': 86}
    xiaoyong_result = {'event_main_type': 87}
    hosptal_result = {}

    with open(STATIC_PATH + 'western_shadow_record_calc_score.json', encoding='utf-8') as f:
        record = json.load(f)

    with open(STATIC_PATH + 'western_shadow_xiaoyong_calc_score.json', encoding='utf-8') as f:
        content = json.load(f)

    with open(STATIC_PATH + 'western_shadow_record_doc_id.json', encoding='utf-8') as f:
        shadow_record_doc_id = json.load(f)

    xiaoyong_total = content['total']
    xiaoyong_detail = content['detail']

    query = WesternShadowMenuProject.query.order_by('project').all()
    try:
        for que in query:
            project = str(que.project)
            basic = json.loads(que.basic)
            localization = json.loads(que.localization)
            score_type_list = json.loads(que.score_type_list)
            reward = json.loads(que.reward)
            rank_reward_score_limit = int(que.rank_reward_score_limit)
            hosptal = json.loads(que.hosptal)
            revive = json.loads(que.revive)
            _tag = basic['_tag'] if '_tag' in basic else []

            # 活动主页
            if is_push == 1 or event_num == 0:
                menu_event_ui = basic['main_event_ui']
                menu_loc = localization['menu_loc']

                calendar_order = basic['calendar_order'] if 'calendar_order' in basic else 1
                calendar_jump = basic['calendar_jump'] if 'calendar_jump' in basic else 1
                top_reward = RewardToTMysqlNew(basic['top_reward'])

                if 'common_buff_pid_1' in basic:
                    common_buff_pid_1 = basic['common_buff_pid_1']
                else:
                    common_buff_pid_1 = -1

                if 'common_buff_pid_2' in basic:
                    common_buff_pid_2 = basic['common_buff_pid_2']
                else:
                    common_buff_pid_2 = -1

                if 'calendar_doc_id' in basic:
                    _calendar_doc_id = basic['calendar_doc_id']
                else:
                    _calendar_doc_id = 1

                menu_result[project] = {
                    '_tag': _tag,
                    'basic': {'event_ui': menu_event_ui},
                    'localization': menu_loc,
                    'exchange_shop': basic['exchange_shop'],
                    'top_reward': top_reward,
                    'calendar_conf': {
                        'event_type': 85,
                        'event_ui': menu_event_ui,
                        'order': 1,
                        'jump': 1,
                        'localization': {
                            'title': _calendar_doc_id,
                            'info': _calendar_doc_id
                        },
                        'reward': top_reward,
                        'show_type': 0
                    },
                    'common_buff_pid_1': common_buff_pid_1,
                    'common_buff_pid_2': common_buff_pid_2
                }

            # 西部暗影录
            if is_push == 1 or event_num == 1:
                record_event_ui = basic['record_event_ui']
                record_loc = localization['record_loc']
                record_calc_score = {
                    'score_type_list': record['score_type_list']
                }
                record_rank_reward = reward['record_rank_reward']
                for node in record_rank_reward:
                    node['reward'] = RewardToTMysqlNew(node['reward'])
                record_result[project] = {
                    '_tag': _tag,
                    'basic': {'event_ui': record_event_ui},
                    'localization': record_loc,
                    'calc_score': record_calc_score,
                    'reward': {'rank_reward': {'user': record_rank_reward}}
                }

            # 骁勇榜
            if is_push == 1 or event_num == 2:
                xiaoyong_event_ui = basic['xiaoyong_event_ui']
                xiaoyong_loc = localization['xiaoyong_loc']
                for node in score_type_list:
                    # 解耦处理
                    task_type = node['type']
                    lv = node['id_list'][0]
                    node['doc_id'] = shadow_record_doc_id[str(task_type)][str(lv)]
                    if 'task_id' in node:
                        del node['task_id']
                    if 'taks_id' in node:
                        del node['taks_id']
                xiaoyong_calc_score = {
                    'score_type_list': score_type_list
                }
                xiaoyong_rank_reward = reward['xiaoyong_rank_reward']
                xiaoyong_goal_reward = reward['xiaoyong_goal_reward']
                for node in xiaoyong_rank_reward:
                    node['reward'] = RewardToTMysqlNew(node['reward'])
                for node in xiaoyong_goal_reward:
                    node['reward'] = RewardToTMysqlNew(node['reward'])
                    node['from'] = 1

                xiaoyong_result[project] = {
                    '_tag': _tag,
                    'basic': {'event_ui': xiaoyong_event_ui},
                    'localization': xiaoyong_loc,
                    'calc_score': xiaoyong_calc_score,
                    'reward': {'goal_reward': {'user': xiaoyong_goal_reward},
                               'rank_reward': {'user': xiaoyong_rank_reward}},
                    'extern0': {'rank_reward_score_limit': rank_reward_score_limit}
                }

            # 医院
            # 20220621 修改医院的生成逻辑 不需要to，由from单独做key
            # 20220804 医院协议修改 增加 switch 字段，厄运暗影默认为1
            # 20230109 医院协议修改 增加 revive_switch 字段，默认为0; 增加revive字段
            if is_push == 1 or event_num == 3:
                hosptal_event_ui = basic['hosptal_event_ui']
                hospital_loc = localization['hospital_loc']
                new_hosptal = {}
                for node in hosptal:
                    hosptal_from = node['from']
                    hosptal_ratio = node['ratio']
                    new_hosptal[str(hosptal_from)] = hosptal_ratio*100
                revive_switch = revive['revive_switch'] if 'revive_switch' in revive else 0
                revive_table = revive['revive_table'] if 'revive_table' in revive else []
                new_revive = {}
                for node in revive_table:
                    revive_to = str(node['to'])
                    new_revive[revive_to] = RewardToTMysqlNew(node['reward'])
                hosptal_result[project] = {
                    'switch': 1,
                    'basic': {'event_ui': hosptal_event_ui},
                    'localization': hospital_loc,
                    'hosptal': new_hosptal,
                    'revive_switch': revive_switch,
                    'troop_num_unit': 1,
                    'revive': new_revive
                }
    except:
        res = {'msg': '发布失败', 'ret': 0}
        return jsonify(res)

    if is_push ==0:
        if event_num == 0:
            response = DownLoad('western_shadow_menu_project',
                                menu_result, is_push)
        elif event_num == 1:
            response = DownLoad('western_shadow_record_project',
                                record_result, is_push)
        elif event_num == 2:
            response = DownLoad('western_shadow_xiaoyong_project',
                                xiaoyong_result, is_push)
        elif event_num == 3:
            response = DownLoad('event_hosptal_project.western_shadow',
                                hosptal_result, is_push)
    elif is_push == 1:
        response = DownLoad('western_shadow_menu_project',
                            menu_result, is_push)
        response = DownLoad('western_shadow_record_project',
                            record_result, is_push)
        response = DownLoad('western_shadow_xiaoyong_project',
                            xiaoyong_result, is_push)
        response = DownLoad('event_hosptal_project.western_shadow',
                            hosptal_result, is_push)
    return response


@app.route('/kvk_event_project', methods=['GET'])
def kvk_event_project():
    query = KvkEventProject.query.order_by('project').all()
    result = []
    for que in query:
        project = int(que.project)
        basic = json.loads(que.basic)
        tmp = {"project": project,'remark': que.remark}
        result.append(tmp)
    return jsonify(result)


@app.route('/kvk_event_project_action', methods=['POST'])
def kvk_event_project_action():
    update_data = json.loads(request.data)
    result = {'msg': '成功', 'ret': 0,}
    _type = update_data['type']
    project = update_data['project']

    project_data = KvkEventProject.query.filter_by(project=project).first()

    if _type == 'remark':
        remark = update_data['remark']
        project_data.remark = str(remark)
        db.session.commit()

    elif _type == 'clone':
        new_project_data = KvkEventProject(
            basic=project_data.basic,
            localization=project_data.localization,
            top_reward=project_data.top_reward,
            user_goal_reward_list=project_data.user_goal_reward_list,
            al_goal_reward_list=project_data.al_goal_reward_list,
            user_rank_reward=project_data.user_rank_reward,
            win_reward=project_data.win_reward,
            lost_reward=project_data.lost_reward,
            score_type_list=project_data.score_type_list,
            hosptal=project_data.hosptal,
            remark=project_data.remark,
            old_localization=project_data.old_localization,
            revive=project_data.revive
            )

        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if new_project_id is None:
            result = {'msg': '克隆失败', 'ret': 2}
        else:
            result = {'msg': '克隆成功', 'ret': 0}

    elif _type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = KvkEventProject.query.filter_by(project=project).first()
        if new_project_data is None:
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}

    elif _type == 'basic':
        basic_data = json.loads(project_data.basic)
        top_reward = json.loads(project_data.top_reward)
        localization = json.loads(project_data.localization)

        if 'kvk_event_ui' not in basic_data:
            basic_data['kvk_event_ui'] = 1005
        if 'event_type' not in basic_data:
            basic_data['event_type'] = 0
        if 'wild_id' not in basic_data:
            basic_data['wild_id'] = 106
        if 'share_mode' not in basic_data:
            basic_data['share_mode'] = 1
        if '_tag' not in basic_data:
            basic_data['_tag'] = []
        if 'hospital_doc_id' in localization:
            del localization['hospital_doc_id']

        common_buff_project = read_s3_file('common_buff_project')
        common_buff_list = []
        for node in common_buff_project:
            common_buff_list.append({
                'label': '{0}-{1}'.format(node['value'], node['label']),
                'value': node['value']
                })

        doc_content = GetDocByFilename('kvk_event')
        doc_id_list = []
        for k, v in doc_content.items():
            doc_id_list.append({
                'value': int(k),
                'label': '{0}-{1}'.format(k, v['title'])
                })

        result['basic_data'] = basic_data
        result['top_reward'] = top_reward
        result['loc'] = localization
        result['common_buff_list'] = common_buff_list
        result['doc_id_list'] = doc_id_list

    elif _type == 'update_basic':
        basic_data = update_data['basic_data']
        top_reward = update_data['top_reward']
        project_data.basic = json.dumps(basic_data)
        project_data.top_reward = json.dumps(top_reward)
        db.session.commit()

    elif _type == 'user_rank_reward':
        user_rank_reward = json.loads(project_data.user_rank_reward)
        for i in range(len(user_rank_reward)):
            node = user_rank_reward[i]
            node['idx'] = i
        result['user_rank_reward'] = user_rank_reward

    elif _type == 'update_user_rank_reward':
        user_rank_reward = update_data['user_rank_reward']
        for node in user_rank_reward:
            if 'idx' in node:
                del node['idx']
        project_data.user_rank_reward = json.dumps(user_rank_reward)
        db.session.commit()
        result['msg'] = '更新成功'

    elif _type == 'user_goal_reward_list':
        user_goal_reward_list = json.loads(project_data.user_goal_reward_list)
        for i in range(len(user_goal_reward_list)):
            node = user_goal_reward_list[i]
            node['idx'] = i
        result['goal_reward'] = user_goal_reward_list

    elif _type == 'update_user_goal_reward_list':
        user_goal_reward_list = update_data['goal_reward']
        for node in user_goal_reward_list:
            if 'idx' in node:
                del node['idx']
        project_data.user_goal_reward_list = json.dumps(user_goal_reward_list)
        db.session.commit()
        result['msg'] = '更新成功'

    elif _type == 'al_goal_reward_list':
        al_goal_reward_list = json.loads(project_data.al_goal_reward_list)
        for i in range(len(al_goal_reward_list)):
            node = al_goal_reward_list[i]
            node['idx'] = i
        result['goal_reward'] = al_goal_reward_list

    elif _type == 'update_al_goal_reward_list':
        al_goal_reward_list = update_data['goal_reward']
        for node in al_goal_reward_list:
            if 'idx' in node:
                del node['idx']
        project_data.al_goal_reward_list = json.dumps(al_goal_reward_list)
        db.session.commit()
        result['msg'] = '更新成功'

    elif _type == 'contribution_rank_reward':
        win_reward = json.loads(project_data.win_reward)
        lost_reward = json.loads(project_data.lost_reward)

        if 'reward' not in win_reward:
            win_reward['reward'] = []
        if 'reward' not in lost_reward:
            lost_reward['reward'] = []
        for i in range(len(win_reward['reward'])):
            win_reward['reward'][i]['idx'] = i
        for i in range(len(lost_reward['reward'])):
            lost_reward['reward'][i]['idx'] = i

        result['win_reward'] = win_reward
        result['lost_reward'] = lost_reward

    elif _type == 'update_contribution_rank_reward':
        win_reward = update_data['win_reward']
        lost_reward = update_data['lost_reward']
        for node in win_reward['reward']:
            if 'idx' in node:
                del node['idx']
        for node in lost_reward['reward']:
            if 'idx' in node:
                del node['idx']

        project_data.win_reward = json.dumps(win_reward)
        project_data.lost_reward = json.dumps(lost_reward)
        db.session.commit()
        result['msg'] = '更新成功'

    elif _type == 'score_type_list':
        score_type_list = json.loads(project_data.score_type_list)
        for i in range(len(score_type_list)):
            score_type_list[i]['idx'] = i

        with open(STATIC_PATH + 'kvk_event_task_pool.json', encoding='utf-8') as f:
            task_pool = json.load(f)

        total_score_type_list = []
        for node in task_pool:
            tmp = {'label': '{0}-{1}'.format(node['idx'], node['label']),
                   'value': node['idx'],
                   'score_type': node['score_type']}
            total_score_type_list.append(tmp)

        result['score_type_list'] = score_type_list
        result['total_score_type_list'] = total_score_type_list

    elif _type == 'update_score_type_list':
        score_type_list = update_data['score_type_list']
        for node in score_type_list:
            if 'idx' in node:
                del node['idx']
        project_data.score_type_list = json.dumps(score_type_list)
        db.session.commit()
        result['msg'] = '更新成功'

    elif _type == 'hosptal':
        hosptal = json.loads(project_data.hosptal)
        for i in range(len(hosptal)):
            hosptal[i]['idx'] = i

        result['hosptal'] = hosptal

    elif _type == 'update_hosptal':
        hosptal = update_data['hosptal']
        for node in hosptal:
            if 'idx' in node:
                del node['idx']
            if 'gap' in node:
                del node['gap']
        project_data.hosptal = json.dumps(hosptal)
        db.session.commit()
        result['msg'] = '更新成功'

    elif _type == 'revive':
        revive = json.loads(project_data.revive)
        if 'revive_switch' not in revive:
            revive['revive_switch'] = 0
        if 'revive_table' not in revive:
            revive['revive_table'] = []
        else:
            for i in range(len(revive['revive_table'])):
                revive['revive_table'][i]['idx'] = i
        result['revive_switch'] = revive['revive_switch']
        result['revive_table'] = revive['revive_table']

    elif _type == 'update_revive':
        revive_table = update_data['revive_table']
        revive_switch = update_data['revive_switch']
        project_data.revive = json.dumps({
            'revive_table': revive_table,
            'revive_switch': revive_switch
            })
        db.session.commit()
        result['msg'] = '更新成功'

    return jsonify(result)


@app.route('/kvk_event_project_down/<int:is_push>/<int:event_num>', methods=['GET', 'POST'])
def kvk_event_project_down(is_push, event_num):
    event_res = {}
    menu_res = {}
    hosptal_res = {}

    with open(STATIC_PATH + 'kvk_event_task_pool.json', encoding='utf-8') as f:
        task_pool = json.load(f)

    with open(STATIC_PATH + 'calc_score_a3.json', encoding='utf-8') as f:
        content = json.load(f)

    with open(STATIC_PATH + 'kvk_event_old_score_type.json', encoding='utf-8') as f:
        old_score_list = json.load(f)

    kingdom_building_score_list = content['kingdom_building_score_list']
    kingdom_score_type_list = content['kingdom_score_type_list']
    user_building_score_list = content['user_building_score_list']
    user_score_type_list = content['user_score_type_list']

    query = KvkEventProject.query.order_by('project').all()
    try:
        for que in query:
            project = str(que.project)
            basic = json.loads(que.basic)
            localization = json.loads(que.localization)
            top_reward = json.loads(que.top_reward)
            user_goal_reward_list = json.loads(que.user_goal_reward_list)
            al_goal_reward_list = json.loads(que.al_goal_reward_list)
            user_rank_reward = json.loads(que.user_rank_reward)
            win_reward = json.loads(que.win_reward)
            lost_reward = json.loads(que.lost_reward)
            score_type_list = json.loads(que.score_type_list)
            hosptal = json.loads(que.hosptal)
            remark = que.remark
            # 20220804 协议修改 增加 localization 字段来兼容旧版本
            old_localization = json.loads(que.old_localization)
            revive = json.loads(que.revive)

            # 20220804 通过 version 来决定活动医院的 switch 字段
            # version = 0 => switch = 0; version = 1 => switch = 1
            version = basic['version']
            if version == 0:
                switch = 0
            elif version == 1:
                switch = 1

            top_reward = RewardToTMysqlNew(top_reward)
            for node in user_goal_reward_list:
                node['from'] = 1
                node['reward'] = RewardToTMysqlNew(node['reward'])
            for node in al_goal_reward_list:
                node['from'] = 1
                node['reward'] = RewardToTMysqlNew(node['reward'])
            for node in user_rank_reward:
                node['reward'] = RewardToTMysqlNew(node['reward'])
            for node in win_reward['reward']:
                node['reward'] = RewardToTMysqlNew(node['reward'])
            for node in lost_reward['reward']:
                node['reward'] = RewardToTMysqlNew(node['reward'])

            new_score_type_list = []
            for node in score_type_list:
                task_idx = node['type']
                for task_node in task_pool:
                    if task_idx == task_node['idx']:
                        tmp = {
                            'division': node['division'],
                            'doc_id': task_node['doc_id'],
                            'points': node['points'],
                            'score_id_map': task_node['score_id_map'],
                            'score_rule_type': task_node['score_rule_type'],
                            'score_type': task_node['score_type']
                        }
                        new_score_type_list.append(tmp)
                        break

            # 20220804 score_type_list 增加doc 兼容旧版本
            for node in new_score_type_list:
                score_type = node['score_type']
                raw_doc = old_score_list[str(score_type)]
                node['doc'] = dealKvkOldScoreDoc(node, raw_doc)

            doc_id = localization['doc_id']
            hospital_doc_id = localization['hospital_doc_id']

            _tag = basic['_tag'] if '_tag' in basic else []

            # kvk_event_project
            if is_push == 1 or event_num == 0:
                if 'common_buff_pid' in basic:
                    common_buff_pid = basic['common_buff_pid']
                    del basic['common_buff_pid']
                else:
                    common_buff_pid = -1

                if 'calendar_doc_id' in basic:
                    _calendar_doc_id = basic['calendar_doc_id']
                else:
                    _calendar_doc_id = 1

                event_tmp = {
                    '_tag': _tag,
                    'calendar_conf': {
                        'event_type': 15,
                        'event_ui': basic['kvk_event_ui'],
                        'order': 1,
                        'jump': 1,
                        'localization': {
                            'title': _calendar_doc_id,
                            'info': _calendar_doc_id
                        },
                        'reward': top_reward,
                        'show_type': 0
                    },
                    'basic':{
                        'event_ui': basic['kvk_event_ui'],
                        'event_type': basic['event_type'],
                        'share_mode': basic['share_mode'],
                        'version': basic['version']
                    },
                    'localization': old_localization,
                    'doc': {
                        'title': doc_id, 'info': doc_id, 'content': doc_id
                    },
                    'victory_reward': {'wild_id': basic['wild_id']},
                    'reward': {
                        'top_reward': top_reward,
                        'goal_reward': {
                            'user_goal_reward_list': user_goal_reward_list,
                            'al_goal_reward_list': al_goal_reward_list
                        },
                        'rank_reward':{
                            'user_rank_reward': user_rank_reward
                        },
                        'contribution_reward': {
                            'win': win_reward,
                            'lost': lost_reward
                        }
                    },
                    'calc_score': {
                        'kingdom_building_score_list': kingdom_building_score_list,
                        'kingdom_score_type_list': kingdom_score_type_list,
                        'score_type_list': new_score_type_list,
                        'user_building_score_list': user_building_score_list,
                        'user_score_type_list': user_score_type_list
                    },
                    '_remark': remark,
                    'common_buff_pid': common_buff_pid
                }
                event_res[project] = event_tmp

            # kvk_menu_project
            if is_push == 1 or event_num == 1:
                menu_tmp = {
                    'basic': {
                        'event_ui': basic['kvk_event_ui'],
                        'version': basic['version']
                    },
                    'localization': {
                        'title': doc_id, 'info': doc_id, 'content': doc_id
                    }
                }
                menu_res[project] = menu_tmp

            # event_hosptal_project.kvk.json
            if is_push == 1 or event_num == 2:
                new_hosptal = {}
                for node in hosptal:
                    new_hosptal[str(node['from'])] = node['ratio']*100
                revive_switch = revive['revive_switch'] if 'revive_switch' in revive else 0
                revive_table = revive['revive_table'] if 'revive_table' in revive else []
                new_revive = {}
                for node in revive_table:
                    revive_to = str(node['to'])
                    new_revive[revive_to] = RewardToTMysqlNew(node['reward'])
                hosptal_tmp = {
                    'switch': switch,
                    'basic': {'event_ui': basic['hosptal_event_ui']},
                    'localization': {
                        'title': hospital_doc_id,
                        'info': hospital_doc_id,
                        'content': hospital_doc_id
                    },
                    'hosptal': new_hosptal,
                    'revive_switch': revive_switch,
                    'troop_num_unit': 1,
                    'revive': new_revive
                }
                hosptal_res[project] = hosptal_tmp

    except:
        res = {'msg': '发布失败', 'ret': 0}
        return jsonify(res)

    if is_push ==0:
        if event_num == 0:
            response = DownLoad('kvk_event_project',
                                event_res, is_push)
        elif event_num == 1:
            response = DownLoad('kvk_event_menu_project',
                                menu_res, is_push)
        elif event_num == 2:
            response = DownLoad('event_hosptal_project.kvk',
                                hosptal_res, is_push)

    elif is_push == 1:
        md5_object = get_file_compare_md5_default_object('kvk')
        md5 = DownLoad_get_md5('kvk_event_project', event_res, is_push)
        if 'kvk_event_project' in md5_object:
            md5_object['kvk_event_project'] = md5
        md5 = DownLoad_get_md5('kvk_event_menu_project', menu_res, is_push)
        if 'kvk_event_menu_project' in md5_object:
            md5_object['kvk_event_menu_project'] = md5
        md5 = DownLoad_get_md5('event_hosptal_project.kvk', hosptal_res, is_push)
        if 'event_hosptal_project.kvk' in md5_object:
            md5_object['event_hosptal_project.kvk'] = md5

        hash = hashlib.md5(json.dumps(md5_object, sort_keys=True).encode('utf-8')).hexdigest()
        data = {}
        query = KvkEventProject.query.order_by('project').all()
        for i in query:
            current_data = i.to_dict()
            data[str(i.project)] = current_data
        new_data = ProjectVersionSnapshot(
            event='kvk',
            hash=hash,
            data=json.dumps(data, sort_keys=True),
            file_info=json.dumps(md5_object),
            created_at=get_current_timestamp()
        )
        db.session.add(new_data)
        db.session.commit()

        response = jsonify({"msg": "发布成功", "ret": 1})

    return response


@app.route('/file_view', methods=['GET'])
def file_view():
    """
    {'idx': int, 'name': str, 'update_time': datetime,
     'md5': str, 'size': int, 's3_path': str}
    """
    result = []
    idx = 1
    with open(STATIC_PATH + 's3_bucket_list.json', encoding='utf-8') as f:
        content = json.load(f)
    for k, v in content.items():
        if k == 'public' or k == 'civilized_kingdom_teleport':
            continue
        elif 'schedule' in k:
            continue
        file_name = k + '.json'
        s3_bucket = v['s3_bucket']
        s3_key = v[EVN]
        try:
            res = s3_client.info_file(s3_bucket, s3_key+file_name)
            tmp = {'idx': idx, 'name': k,
                   'update_time': res['LastModified'].strftime("%Y-%m-%d %H:%M:%S"),
                   'md5': res['ETag'][1:-1],
                   'size': res['ContentLength'] // 1024,
                   's3_path': s3_bucket + '/' + s3_key}
            result.append(tmp)
            idx += 1
        except:
            print('not found {}'.format(file_name))

    return jsonify(result)

@app.route('/file_view_action', methods=['POST'])
def file_view_action():
    update_data = json.loads(request.data)
    result = {'msg': '成功', 'ret': 0,}
    _type = update_data['type']

    if _type == 'load':
        name = update_data['name']
        if name != 'liqisheng':
            result['ret'] = 1

    elif _type == 'download':
        file_name = update_data['file_name']
        file_name_json = file_name + '.json'
        current_dir = os.path.dirname(os.path.realpath(__file__)) + "\\tmp_data"
        with open(STATIC_PATH + 's3_bucket_list.json', encoding='utf-8') as f:
            content = json.load(f)
        s3_bucket = content[file_name]['s3_bucket']
        s3_key = content[file_name][EVN]
        # 没有抓住
        file_content = s3_client.download_file(s3_bucket,
                                               s3_key + file_name_json,
                                               '.\\tmp_data\\' + file_name_json)
        response = make_response(
            send_from_directory(current_dir,
                                file_name_json.encode('utf-8').decode('utf-8'),
                                as_attachment=True))
        response.headers["Content-Disposition"] = "attachment; filename={}".format(
            file_name_json.encode().decode('latin-1'))
        response.headers["Cache-Control"] = "no-cache"
        response.headers["max-age"] = 0

    return jsonify(result)

@app.route('/file_view_down/<file_name>', methods=['GET'])
def file_view_down(file_name):
    result = {'msg': '成功', 'ret': 0,}
    file_name_json = file_name + '.json'
    current_dir = os.path.dirname(os.path.realpath(__file__)) + "\\tmp_data"
    with open(STATIC_PATH + 's3_bucket_list.json', encoding='utf-8') as f:
        content = json.load(f)
    s3_bucket = content[file_name]['s3_bucket']
    s3_key = content[file_name][EVN]
    file_content = s3_client.download_file(s3_bucket,
                                           s3_key + file_name_json,
                                           current_dir + file_name_json)
    file_md5 = s3_client.md5_file(s3_bucket,
                                  s3_key + file_name_json)
    print(file_content)
    print(file_md5)
    # try:
    #     response = make_response(
    #         send_from_directory(current_dir,
    #                             file_name_json.encode('utf-8').decode('utf-8'),
    #                             as_attachment=True))
    #     response.headers["Content-Disposition"] = "attachment; filename={}".format(
    #         file_name_json.encode().decode('latin-1'))
    #     response.headers["Cache-Control"] = "no-cache"
    #     response.headers["max-age"] = 0
    #     return response
    # except:
    #     print('download error in {}'.format(file_name))

    return jsonify(result)


@app.route('/duel_yard_event_proj', methods=['GET'])
def duel_yard_event_proj():
    query = DuelYardEventProj.query.order_by('project').all()
    result = []
    for que in query:
        project = int(que.project)
        loc = json.loads(que.title)
        title = loc['1'] if '1' in loc else '未填写'
        tmp = {'project': project, 'remark': que.remark, 'title': title}
        result.append(tmp)
    return jsonify(result)

@app.route('/duel_yard_event_proj_action', methods=['GET', 'POST'])
def duel_yard_event_proj_action():
    update_data = json.loads(request.data)
    result = {'msg': '成功', 'ret': 0,}
    _type = update_data['type']
    project = update_data['project']

    project_data = DuelYardEventProj.query.filter_by(project=project).first()

    if _type == 'remark':
        remark = update_data['remark']
        project_data.remark = str(remark)
        db.session.commit()

    elif _type == 'clone':
        new_project_data = DuelYardEventProj(
            basic=project_data.basic,
            goal_reward=project_data.goal_reward,
            title=project_data.title,
            remark=project_data.remark)

        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if new_project_id is None:
            result = {'msg': '克隆失败', 'ret': 2}
        else:
            result = {'msg': '克隆成功', 'ret': 0}

    elif _type == 'delete':
        db.session.delete(project_data)
        db.session.commit()
        new_project_data = DuelYardEventProj.query.filter_by(project=project).first()
        if new_project_data is None:
            result = {'msg': '删除成功', 'ret': 0}
        else:
            result = {'msg': '删除失败', 'ret': 1}

    elif _type == 'basic':
        basic_data = json.loads(project_data.basic)
        goal_reward = json.loads(project_data.goal_reward)
        for i in range(len(goal_reward)):
            goal_reward[i]['idx'] = i
        result['basic_data'] = basic_data
        result['goal_reward'] = goal_reward

    elif _type == 'update_basic':
        basic_data = update_data['basic_data']
        goal_reward = update_data['goal_reward']
        for node in goal_reward:
            if 'idx' in node:
                del node['idx']
        project_data.basic = json.dumps(basic_data)
        project_data.goal_reward = json.dumps(goal_reward)
        db.session.commit()

    return jsonify(result)

@app.route('/duel_yard_event_proj_down/<int:is_push>', methods=['GET', 'POST'])
def duel_yard_event_proj_down(is_push):
    result = {}

    query = DuelYardEventProj.query.order_by('project').all()
    for que in query:
        pid = str(que.project)
        basic = json.loads(que.basic)
        goal_reward = json.loads(que.goal_reward)
        title = json.loads(que.title)
        rule_list = [{"detail":[[0,0,[0]]],
                      "doc":{"1":"Normal Shoot Once"},
                      "factor":[0,1],
                      "type":25},
                     {"detail":[[0,0,[1]]],
                      "doc":{"1":"Advanced Shoot Once"},
                      "factor":[0,10],
                      "type":25}]
        for node in goal_reward:
            node['reward'] = RewardToTMysqlDuelYard(node['reward'])

        result[pid] = {'info': {'rule_list': rule_list,
                                'goal_reward': goal_reward,
                                'title': title},
                       'basic': basic}

    response = DownLoad('duel_yard_event_proj', result, is_push)
    return response


@app.route('/loadIapList', methods=['GET', 'POST'])
def loadIapList():
    with open(STATIC_PATH + 'iap_list.json') as f:
        data = json.load(f)
        return json.dumps(data)


@app.route('/load_iap_list', methods=['GET'])
def load_iap_list():
  with open(STATIC_PATH + 'iap_list.json', encoding='utf8') as f:
      data = json.load(f)
  return jsonify({"data":data,"code":0,"msg":''})


@app.route('/loadEquipList', methods=['GET'])
def loadEquipList():
    equip_data = loadEquip()
    doc_data = loadDocument()
    equip_equipment_data = equip_data['equip_equipment']
    equip_equipment_doc_data = doc_data['doc_equipment_sub_series']
    result = {}
    for i in equip_equipment_data:
        if equip_equipment_data[i]['b'][5] != -1:
            eid = str(equip_equipment_data[i]['b'][5])

            if eid in equip_equipment_doc_data:
                result[eid] = equip_equipment_doc_data[eid]['name']
            else:
                result[eid] = 'ERROE'

    result_data = []
    for i in result:
        tmp = {}
        tmp['id'] = int(i)
        tmp['name'] = result[i] + '-' + str(i)
        result_data.append(tmp)

    return json.dumps(result_data)



@app.route('/bonusList/', defaults={'field': 'reward'}, methods=['GET', 'POST'])
@app.route('/bonusList/<field>', methods=['GET', 'POST'])
def bonusList(field):
    raise Exception('This api has been deprecated. Use the new resource api in the front_end.')
    # reward = rewardList()
    # return json.dumps(reward[field])
    try:
        req = requests.post(url=f"{RESOURCE_SERVICE_URL}/get_reward", json={
            'project': PROJECT_NAME,
            'environment': EVN,
            'part': ['reward_list']
        })
        if req.status_code == 200:
            resp = req.json()
            if resp['status'] == 'success':
                return jsonify(resp['reward_list'])
    except Exception as e:
        logging.exception(e)
    return jsonify({})



@app.route('/reward_type_list/', methods=['GET', 'POST'])
def reward_type_list():
    raise Exception('This api has been deprecated. Use the new resource api in the front_end.')
    # with open(STATIC_PATH + 'reward_type_list.json', encoding='utf8') as f:
    #     data = json.load(f)
    # for node in data:
    #     node['name'] = node['name'] + '-' + str(node['type'])
    #     node['label'] = node['label'] + '-' + str(node['type'])
    #
    # return json.dumps(data)
    try:
        req = requests.post(url=f"{RESOURCE_SERVICE_URL}/get_reward", json={
            'project': PROJECT_NAME,
            'environment': EVN,
            'part': ['reward_type_list']
        })
        if req.status_code == 200:
            resp = req.json()
            if resp['status'] == 'success':
                return jsonify(resp['reward_type_list'])
    except Exception as e:
        logging.exception(e)
    return jsonify([])

@app.route('/novice_recharge_bonusList', methods=['GET'])
def novice_recharge_bonusList():
    result = json.loads(bonusList('reward'))
    result_list = result['0']
    with open(GLOBAL_PATH + 'sub_game.json', encoding='utf-8') as f:
        content = json.load(f)
    coupon_content = content['sub_game_coupon_config']

    cash_coupon = list(coupon_content.keys())
    new_reward = []
    for node in result_list:
        if str(node['id']) in cash_coupon:
            new_reward.append(node)
    res = {0: new_reward}
    return jsonify(res)


@app.route('/change_data', methods=['GET'])
def change_data():
    with open(STATIC_PATH + 'event_project.json', encoding='utf8') as f:
        event_project = json.load(f)

    reward_item_list = rewardList()
    reward_item_list = reward_item_list['name']

    new_event_project = {}
    for project, project_data in event_project.items():

        if project not in new_event_project:
            new_event_project[project] = {}

        rank_data = {}
        for r_idx in range(len(project_data['rank'])):
            if str(r_idx) not in rank_data:
                rank_data[str(r_idx)] = {}

            rank_data[str(r_idx)]['condition'] = project_data['rank'][r_idx]['condition']

            goal_data = copy.deepcopy(project_data['rank'][r_idx]['goal'])
            rank_reward_data = copy.deepcopy(project_data['rank'][r_idx]['rank_reward'])

            rank_data[str(r_idx)]['goal'] = {}
            rank_data[str(r_idx)]['rank_reward'] = []

            for g_idx in range(len(goal_data)):
                if str(g_idx) not in rank_data[str(r_idx)]['goal']:
                    rank_data[str(r_idx)]['goal'][str(g_idx)] = []

                for node in goal_data[g_idx]:
                    node['reward'] = RewardShowToDoc(node['reward'], reward_item_list)
                    rank_data[str(r_idx)]['goal'][str(g_idx)].append(node)

            for node in rank_reward_data:
                node['reward'] = RewardShowToDoc(node['reward'], reward_item_list)
                rank_data[str(r_idx)]['rank_reward'].append(node)

        new_event_project[project]['rank'] = rank_data
        new_event_project[project]['event_type'] = project_data['basic']['event_type']


    fh = open(STATIC_PATH + 'extreme_user_event_project_new.json', "w")
    json.dump(new_event_project, fh, sort_keys=True, separators=(',', ':'))
    fh.close()

    return jsonify({"data":[],"code":0,"msg":''})


@app.route('/get_check_tags_list', methods=['POST'])
def get_check_tags_list():
    event_type = request.json.get('event_type')
    project_data = CheckTags.query.filter_by(event_type=event_type).first()
    result = []
    if project_data:
        tags = json.loads(project_data.tags)
        for i in tags:
            result.append({
                "value": i['id'],
                "label": f"{i['id']} - {i['remark']}"
            })
    return json.dumps(result)


@app.route('/get_static_config_file', methods=['POST'])
def get_static_config_file():
    params = json.loads(request.data)
    file_name = params['file_name']
    try:
        with open(STATIC_PATH + f'{file_name}.json', encoding='utf-8') as f:
            file_data = json.load(f)
        return json.dumps({
            'status': 'success',
            'data': file_data
        })
    except Exception as e:
        print('[get_static_config_file] error', flush=True)
        logging.exception(e)
        return json.dumps({
            'status': 'error',
            'data': traceback.format_exc()
        })


@app.route('/update_wg_5_2_1', methods=['POST'])
def update_wg_5_2_1():
    project_data = BattlePass.query.all()
    # 普通季卡添加 doc id
    result = get_doc_id_list_in_operation_event_english('norm_card_event', 'info')
    default_doc_id = -1
    if len(result['doc_id_list']) > 0:
        default_doc_id = result['doc_id_list'][0]['value']
    for i in project_data:
        basic = json.loads(i.basic)
        if 'doc_id' not in basic:
            basic['doc_id'] = default_doc_id
            i.basic = json.dumps(basic)
    db.session.commit()
    return jsonify({
        'status': 'success'
    })


@app.route('/update_wg_5_3', methods=['POST'])
def update_wg_5_3():
    mr_project_data = MultidayRecharge.query.all()
    # 多日充值添加 doc_id
    result = get_doc_id_list_in_operation_event_english('multiday_charge_event', 'title')
    default_doc_id = -1
    if len(result['doc_id_list']) > 0:
        default_doc_id = result['doc_id_list'][0]['value']
    for i in mr_project_data:
        basic = json.loads(i.basic)
        if 'doc_id' not in basic:
            basic['doc_id'] = default_doc_id
            i.basic = json.dumps(basic)

    result = get_doc_id_list_in_operation_event_english('return_event', 'title')
    default_doc_id = -1
    if len(result['doc_id_list']) > 0:
        default_doc_id = result['doc_id_list'][0]['value']
    bf_project_data = BackflowMainProj.query.all()
    for i in bf_project_data:
        basic = json.loads(i.basic)
        # # 回归活动添加活动类型
        # if 'event_type' not in basic:
        #     basic['event_type'] = 0
        # 回归活动添加 open_control
        if 'open_control' not in basic:
            basic['open_control'] = {
                'old': {
                    'login': True,
                    'back_task': True,
                    'back_iap': True,
                    'multiday_recharge': True,
                    'store_treasure': True,
                    'consume': True,
                    'migration': True,
                    'new_journey': True
                },
                'new': {
                    'login': True,
                    'back_task': True,
                    'back_iap': True,
                    'multiday_recharge': True,
                    'store_treasure': True,
                    'benefits': True,
                    'inheritance': True
                }
            }
        # 回归活动添加 doc_id
        if 'doc_id' not in basic:
            basic['doc_id'] = default_doc_id
        if 'new_journey_doc_id' not in basic:
            basic['new_journey_doc_id'] = default_doc_id
        # 回归活动添加冷却时间
        if 'cd' not in basic:
            basic['cd'] = 0
        # 回归活动删除无用 event_ui (写死处理)
        if 'login_ui' in basic:
            del basic['login_ui']
        if 'task_ui' in basic:
            del basic['task_ui']
        if 'consume_ui' in basic:
            del basic['consume_ui']
        if 'iap_ui' in basic:
            del basic['iap_ui']
        if 'migration_ui' in basic:
            del basic['migration_ui']
        i.basic = json.dumps(basic)
        # 回归活动添加回归福利默认值
        if i.benefits is None:
            i.benefits = json.dumps({
                'reward': [],
                'buff': []
            })
        # 回归活动添加新的征程默认值
        if i.new_journey is None:
            i.new_journey = json.dumps({
                'svr_open_time': 0,
                'offline_day': 0,
                'cd': 0,
                'recommend_sid_num': 0
            })
        # 回归活动添加多日充值默认值
        if i.multiday_recharge is None:
            i.multiday_recharge = json.dumps({
                'target': []
            })
        # 回归活动添加商城秘宝默认值
        if i.store_treasure is None:
            i.store_treasure = json.dumps({
                'basic': {
                    'tab_ui': 0,
                    'score_id': 0,
                    'u_score': 0,
                    'iap_pid_list': '',
                    'task_doc_id': 0
                },
                'reward': {
                    'max_task_id': 0,
                    'list': []
                }
            })
        # 回归活动添加荣耀传承默认值
        if i.inheritance is None:
            i.inheritance = json.dumps({
                'basic': {
                    'old_pay_need': 0,
                    'old_pay_limit': 0,
                    'rate': 0,
                    'coupon_list': '',
                    'evip_points': 250,
                    'coupon_rate': 100,
                    'point_rate': 0
                },
                'reward_section': []
            })
        # 新的征程 从回归活动克隆子活动数据
        if i.new_journey_login_reward is None:
            i.new_journey_login_reward = i.login_reward
        if i.new_journey_task_group is None:
            i.new_journey_task_group = i.task_group
        if i.new_journey_score_reward is None:
            i.new_journey_score_reward = i.score_reward
        if i.new_journey_iap_group is None:
            i.new_journey_iap_group = i.iap_group
        if i.new_journey_multiday_recharge is None:
            i.new_journey_multiday_recharge = i.multiday_recharge
        if i.new_journey_store_treasure is None:
            i.new_journey_store_treasure = i.store_treasure

        # 多日充值 / 商城秘宝 添加 doc_id
        data = json.loads(i.multiday_recharge)
        if 'doc_id' not in data:
            data['doc_id'] = default_doc_id
            i.multiday_recharge = json.dumps(data)
        data = json.loads(i.store_treasure)
        if 'doc_id' not in data:
            data['doc_id'] = default_doc_id
            i.store_treasure = json.dumps(data)
        data = json.loads(i.new_journey_multiday_recharge)
        if 'doc_id' not in data:
            data['doc_id'] = default_doc_id
            i.new_journey_multiday_recharge = json.dumps(data)
        data = json.loads(i.new_journey_store_treasure)
        if 'doc_id' not in data:
            data['doc_id'] = default_doc_id
            i.new_journey_store_treasure = json.dumps(data)

    db.session.commit()
    return jsonify({
        'status': 'success'
    })


@app.route('/update_wg_5_3_optimization', methods=['POST'])
def update_wg_5_3_optimization():
    bf_project_data = BackflowMainProj.query.all()
    for i in bf_project_data:
        basic = json.loads(i.basic)
        # 回归活动添加冷却时间单位
        if 'cd_unit' not in basic:
            basic['cd_unit'] = 'day'
        i.basic = json.dumps(basic)

        new_journey = json.loads(i.new_journey)
        # 回归活动添加冷却时间单位
        if 'cd_unit' not in new_journey:
            new_journey['cd_unit'] = 'day'
        i.new_journey = json.dumps(new_journey)
    db.session.commit()
    return jsonify({
        'status': 'success'
    })


@app.after_request
def af_req(resp):  # 解决跨域session丢失
    resp = make_response(resp)
    # resp.headers['Access-Control-Allow-Origin'] = 'http://54.223.156.94:3104'
    # resp.headers['Access-Control-Allow-Origin'] = HOST_1
    origin = request.origin
    resp.headers['Access-Control-Allow-Origin'] = origin
    # if origin in HOST_1:
    #     resp.headers['Access-Control-Allow-Origin'] = origin
    # else:
    #     resp.status_code = 403
    resp.headers['Access-Control-Allow-Methods'] = 'PUT,POST,GET,DELETE,OPTIONS'
    #resp.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    resp.headers['Access-Control-Allow-Headers'] = 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild'
    resp.headers['Access-Control-Allow-Credentials'] = 'true'

    resp.headers['X-Powered-By'] = '3.2.1'
    resp.headers['Content-Type'] = 'application/json;charset=utf-8'
    return resp


if __name__ == '__main__':
    s3_client = S3Operation()
    app.run(debug=True, threaded=True, host=HOST_2, port=PORT)

